import java.awt.*; import java.awt.event.*; import javax.swing.*; public class RobotGetPixelColor { private JFrame frame; private Robot robot; public static void main(String[] args) { new RobotGetPixelColor(); } // Constructor public RobotGetPixelColor() { // Create and set up a JFrame and make it visible frame = new JFrame("Robot Demo: getPixelColor()"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(379, 187); frame.setLocationRelativeTo(null); frame.setBackground(Color.WHITE); frame.add(new MainPane()); frame.setResizable(false); frame.setVisible(true); } // The following claws exists because the "default" JFrame is not being // extended from a class that is capable of painting; in other words, // since a named JFrame ("frame") is being created, it becomes necessary // to create a separate class (below), an instance of which is added to // the JFrame (above), so that a 'paint' method can be overridden; // otherwise, any new 'paint' method that is created will not be called public class MainPane extends JPanel { // Constructor public MainPane() { MouseAdapter mouseHandler = new MouseAdapter() { public void mousePressed(MouseEvent event) { // The 'Robot' class requires exception trapping try { // Note that while 'event.getX()' and 'event.getY()' return the // location of the mouse on the JFrame, the 'getPixelColor()' // method of the 'Robot' class applies its arguments to the // entire screen; the two lines below compensate for that, as // well as for the thickness of the JFrame's border and the // thickness of its title bar int xPos = frame.getX() + event.getX() + 4; int yPos = frame.getY() + event.getY() + 24; // Determine and display the color of the pixel on which the mouse // pointer was clicked (pressed) robot = new Robot(); System.out.println(robot.getPixelColor(xPos, yPos)); } catch (Exception error) { System.out.println("ERROR: " + error.getMessage()); } } }; addMouseListener(mouseHandler); } public void paintComponent(Graphics g) { // Draw ten filled squares to provide a variety of colors that can be clicked g.setColor(Color.RED); g.fillRect(20, 20, 50, 50); g.setColor(Color.GREEN); g.fillRect(90, 20, 50, 50); g.setColor(Color.BLUE); g.fillRect(160, 20, 50, 50); g.setColor(Color.BLACK); g.fillRect(230, 20, 50, 50); g.setColor(Color.YELLOW); g.fillRect(300, 20, 50, 50); g.setColor(Color.ORANGE); g.fillRect(20, 90, 50, 50); g.setColor(Color.PINK); g.fillRect(90, 90, 50, 50); g.setColor(Color.MAGENTA); g.fillRect(160, 90, 50, 50); g.setColor(Color.CYAN); g.fillRect(230, 90, 50, 50); g.setColor(Color.GRAY); g.fillRect(300, 90, 50, 50); } } }