获取鼠标光标下的RGB值

时间:2013-04-25 15:33:09

标签: java

我遇到了这段代码的问题。我希望能够移动鼠标并获得鼠标所在的像素值(红色,绿色,蓝色)。我无法使用“getRGB”。你会如何开始呢。有人能指出我正确的方向。

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

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

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


    int red = getred();
    int green= getgreen();
    int blue= getblue();
    int color = new Color (red,green,blue).getRGB();

    while(true) {
        coord = MouseInfo.getPointerInfo().getLocation();  
        color = getred();

        {
    System.out.println(getRGB());




        }

2 个答案:

答案 0 :(得分:1)

研究使用Robot的getPixelColor方法:

color = robot.getPixelColor(coord.x, coord.y);

如,

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

public class PixelColor {
   private static final long SLEEP_DELAY = 400L;

   public static void main(String[] args) {
      Point coord;
      Robot robot = null;

      try {
         robot = new Robot();
      } catch (AWTException e) {
         e.printStackTrace();
         System.exit(-1);
      }

      Color color = null;
      while (true) {
         coord = MouseInfo.getPointerInfo().getLocation();
         color = robot.getPixelColor(coord.x, coord.y);
         System.out.println(color);
         try {
            Thread.sleep(SLEEP_DELAY);
         } catch (InterruptedException e) {}
      }
   }
}

答案 1 :(得分:0)

要获得鼠标指针所在的像素颜色,您必须在每个指针中获得鼠标位置 迭代循环,然后使用机器人的getPixelColor方法。

while(true) 
{
    pointer = MouseInfo.getPointerInfo();
    coord = pointer.getLocation();
    System.out.print(coord.x + " " + coord.y);
    System.out.println(" color: " + robot.getPixelColor(coord.x, coord.y).getRed() +                                             
                           ", " + robot.getPixelColor(coord.x, coord.y).getGreen() + 
                ", " + robot.getPixelColor(coord.x, coord.y).getBlue());
}