Jaanus
Jaanus

Reputation: 16531

Java get color of pixel LIVE

I have a problem with finding the current color under the cursor.

My code:

import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.PointerInfo;
import java.awt.Robot;

public class Test {
    public static void main(String[] args) throws Exception {
        PointerInfo pointer;
        pointer = MouseInfo.getPointerInfo();
        Point coord = pointer.getLocation();

        Robot robot = new Robot();
        robot.delay(2000);

        while(true) {
            coord = MouseInfo.getPointerInfo().getLocation();       
            Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getX());
            if(color.getGreen() == 255 && color.getBlue() == 255 && color.getRed() == 255) {
                System.out.println("WHITE FOUND");
            }
            robot.delay(1000);
        }
    }
}

When I run it, even when I hold my mouse on the gray area, I am getting “WHITE FOUND WHITE FOUND” message.

What can be the problem? Can you guys test if it does not work for you also?

Added Picture: I am holding my cursor on Eclipse gray area but getting “WHITE FOUND” message.

enter image description here

Upvotes: 5

Views: 10700

Answers (3)

trashgod
trashgod

Reputation: 205775

You might also like Zoom, which uses the related method createScreenCapture() to collect screen pixels en masse and display color information about each in a tool tip.

Upvotes: 0

ronash
ronash

Reputation: 866

You're using getX() twice. [min length]

Upvotes: 2

MBU
MBU

Reputation: 5098

I think the problem is you are using getX twice instead of getX and getY

Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getX())

Should be

Color color = robot.getPixelColor((int)coord.getX(), (int)coord.getY())

Upvotes: 6

Related Questions