Search code examples
javacolorsawtrobot

Java robot not reading color running


When the given pixel is white, robot behaves as predicted. But when i test it on a different color and then change to white its still stuck in loop:

(...)
stuck in while->else
false
(...)

What might be the problem? Here is the code:

public class test {
public static boolean ifFinished = false;

public static void main(String[] args) throws AWTException, IOException,
        InterruptedException {
    // Create a Robot object
    Robot myRobot = new Robot();

    // pick a color of given pixels
    Color color = myRobot.getPixelColor(912, 487);

    System.out.println("Red color of pixel   = " + color.getRed());
    System.out.println("Green color of pixel = " + color.getGreen());
    System.out.println("Blue color of pixel  = " + color.getBlue());

    while (ifFinished == false) {
        //Checks if color is white
        if (color.getRed() == 255 && color.getGreen() == 255
                && color.getBlue() == 255) {
            ifFinished = true;  //if it is set ifFinished to true
            System.out.println("stuck in while->if");
        } else
            Thread.sleep(1000);
        ifFinished = false;
        System.out.println("stuck in while->else");
        System.out.println(ifFinished);
    }
}

}

Solution

  • You need to move the line that gets the fetches the color using Robot inside the loop, otherwise it will never be updated.

    while (ifFinished == false) {
    
        Color color = myRobot.getPixelColor(912, 487);   // <==== move inside loop
    
        System.out.println("Red color of pixel   = " + color.getRed());
        System.out.println("Green color of pixel = " + color.getGreen());
        System.out.println("Blue color of pixel  = " + color.getBlue());
    
        //Checks if color is white
        if (color.getRed() == 255 && color.getGreen() == 255
                && color.getBlue() == 255) {
            ifFinished = true;  //if it is set ifFinished to true
            System.out.println("stuck in while->if");
        } else
            Thread.sleep(1000);
        ifFinished = false;
        System.out.println("stuck in while->else");
        System.out.println(ifFinished);
    }