问题
I want to find the colour of a specific pixel on the screen. The background of the JFrame is set to white, which is RGB(255, 255, 255). The Graphics object is set to black, which is RGB(0, 0, 0).
I draw a rectangle. (100, 100) is a pixel on the outline of the rectangle.
Before drawing, I get the pixel colour of (100, 100) and it gives RGB(255, 255, 255). After drawing, I get the pixel colour of (100, 100) and it gives RGB(255, 255, 255). Is it not supposed to be RGB(0, 0, 0)? Also, the output repeats twice. Why?
The code:
public void paintComponent(Graphics g){
Robot robot = null;
try {
robot = new Robot();
} catch (AWTException e) {
e.printStackTrace();
}
Color pixelColour;
g.setColor(Color.black);
pixelColour = robot.getPixelColor(100, 100);
System.out.println("Pixel colour at (100, 100) before drawing: " + pixelColour.toString());
g.drawLine(100, 100, 100, 200);
g.drawLine(100, 200, 300, 200);
g.drawLine(300, 200, 300, 100);
g.drawLine(300, 100, 100, 100);
pixelColour = robot.getPixelColor(100, 100);
System.out.println("Pixel colour at (100, 100) after drawing: " + pixelColour.toString());
}
public static void main(String[] args)
{
PixelColour pc = new PixelColour();
JFrame frame = new JFrame("Pixel colour");
frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
frame.getContentPane().add(pc);
frame.setSize(500,500);
frame.setBackground(Color.white);
frame.setVisible(true);
}
}
The output:
Pixel colour at (100, 100) before drawing: java.awt.Color[r=255,g=255,b=255]
Pixel colour at (100, 100) after drawing: java.awt.Color[r=255,g=255,b=255]
Pixel colour at (100, 100) before drawing: java.awt.Color[r=255,g=255,b=255]
Pixel colour at (100, 100) after drawing: java.awt.Color[r=255,g=255,b=255]
回答1:
The Robot grabs a pixelcolor at a specific screen coordinate. With the origin on the top left of your screen. It does not know about your window. You draw your pixels relative to your parent component. The origin of your PixelColor component is the top left corner of the viewing area of your JFrame. In order to get the screen coordinate of a pixel you can use SwingUtilities:
SwingUtilities.convertPointToScreen(point, component);
https://docs.oracle.com/javase/7/docs/api/javax/swing/SwingUtilities.html#convertPointToScreen(java.awt.Point,%20java.awt.Component)
Point screenLocation = SwingUtilities.convertPointToScreen(new Point(100, 100), this);
pixelColour = robot.getPixelColor(screenLocation.x, screenLocation.y);
The reason the Robot gives you white at the moment is probably just a coincidence.
Also your code is running twice because Swing decides to call it twice. If Swing thinks components need to redraw, for example when resizing it calls paintComponent. Theres nothing you can do about it.
来源:https://stackoverflow.com/questions/36246988/cannot-get-colour-of-pixel-on-screen