I am writing code that takes a picture of the screen and then checks pixel by pixel looking for a certain RGB value. Then I want to make it so that it clicks once on that RGB value and then breaks, but for some reason the loop keeps running through all the pixels, ignoring the break command that I put in and clicking on all the pixels of that color instead of clicking once. Any solutions?
for (int i=0; i<image.getWidth()-1; i++){
x += 1;
int y = 0;
for (int j=0; j<image.getHeight()-1; j++){
y += 1;
int c = image.getRGB(x,y);
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
// and the Java Color is ...
Color color = new Color(red,green,blue);
Color iron = new Color(0,255,0);
if (color.equals(iron)){
Robot move = new Robot();
move.mouseMove(x,y);
Thread.sleep(500);
move.mousePress(InputEvent.BUTTON1_DOWN_MASK);
move.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println(iron);
break;
}
}
}
>Solution :
what you can do is create a flag variable outside your 1st for loop and set it as false. In your 1st loop check if the flag is true and if the condition is true break the loop, in the else part you can run you’re second for loop, and when the condition is true in your 2nd loop. set the flag high and break the inner loop.
flag = false;
for (int i=0; i<image.getWidth()-1; i++){
if(flag)
break;
x += 1;
int y = 0;
for (int j=0; j<image.getHeight()-1; j++){
y += 1;
int c = image.getRGB(x,y);
int red = (c & 0x00ff0000) >> 16;
int green = (c & 0x0000ff00) >> 8;
int blue = c & 0x000000ff;
// and the Java Color is ...
Color color = new Color(red,green,blue);
Color iron = new Color(0,255,0);
if (color.equals(iron)){
Robot move = new Robot();
move.mouseMove(x,y);
Thread.sleep(500);
move.mousePress(InputEvent.BUTTON1_DOWN_MASK);
move.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
System.out.println(iron);
flag = true;
break;
}
}
}