Java Graphics How to - Get the color for a set of coordinates relative to the screen or the GraphicsDevice








Question

We would like to know how to get the color for a set of coordinates relative to the screen or the GraphicsDevice.

Answer

import java.awt.AWTException;
import java.awt.Color;
import java.awt.MouseInfo;
import java.awt.Point;
import java.awt.Robot;
//  w w  w .j  ava2 s .  c  om
public class Main {

  public static void main(String[] args) throws Exception {
    System.out.println(getPointerColor());
  }

  public static Color getPointerColor() throws AWTException {
    Point coordinates = MouseInfo.getPointerInfo().getLocation();
    Robot robot = new Robot();
    return robot.getPixelColor((int) coordinates.getX(),
        (int) coordinates.getX());
  }
}

The code above generates the following result.