I am trying to create an application similar to DigitalColor Meter in Mac OS X. (Note: DigitalColor Meter is a small application for Mas OS to pick pixel colour below the mouse cursor).
To implement it in Java, I have tried using AWTRobot getPixelColor() but getPixelColor() seems to be not efficient. Below is my code:
public class AWT_Robot {
public static void main(String[] args) {
int mouseX = 0;
int mouseY = 0;
try {
Robot robot = new Robot();
while(true){
robot.delay(1000);
mouseX = MouseInfo.getPointerInfo().getLocation().x;
mouseY = MouseInfo.getPointerInfo().getLocation().x;
Color color = robot.getPixelColor(mouseX, mouseY);
System.out.println("x: "+mouseX+" y: "+mouseY+" RGB: ("+color.getRed()+", "+color.getGreen()+", "+color.getBlue()+")");
}
} catch (AWTException e) {
e.printStackTrace();
}
}
}
When I hovered the mouse over a red image (RGB: 243,0,0), it prints with varying RGB as below:
x: 313 y: 313 RGB: (239, 0, 0)
x: 313 y: 313 RGB: (239, 0, 0)
x: 294 y: 294 RGB: (239, 0, 0)
x: 186 y: 186 RGB: (79, 116, 163)
x: 104 y: 104 RGB: (67, 104, 154)
x: 116 y: 116 RGB: (79, 117, 164)
x: 159 y: 159 RGB: (68, 105, 155)
1) What could be the reason behind this issue?
2) Also is there any other way to implement the application (DigitalColor Meter) in Java?
I found similar questions in the below links but none of them seem to have the answer that I am expecting.
java robot.getPixelColor(x,y) question
Your mouseX
and mouseY
are both gotten using getLocation().x
. This is likely the cause of your problem.