在屏幕Java上获取像素颜色?

时间:2014-03-06 06:48:44

标签: swing colors jframe rgb getpixel

您好我正在尝试获取JFrame上特定像素的颜色。

这是我的代码。我的画框是红色的。

我遇到的问题是当我点击框架它应该返回红色的RGB颜色(255,0,0),但是当我点击不同的点时,我有时会得到白色的RGB颜色(255,255,255)我的代码人员有什么问题?

public class guiTest extends JFrame 
{

    private static Shape ellipse;   
     private static Robot rb;

    public guiTest()
    {
    super("4-connected approach");
    setLayout(new FlowLayout());
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setSize(800,800);
    this.getContentPane().setBackground(Color.red);
    setLocationRelativeTo(null);
    addMouseListener(new MouseListener(){
        @Override
        public void mouseClicked(MouseEvent e) {
            System.out.println("Pixel:"+e.getX()+","+e.getY());             
            try {
                System.out.println(getPixel(e.getX(),e.getY()));
            } catch (AWTException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            }

        }

        @Override
        public void mouseEntered(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseExited(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mousePressed(MouseEvent e) {
            // TODO Auto-generated method stub

        }

        @Override
        public void mouseReleased(MouseEvent e) {
            // TODO Auto-generated method stub

        }


    });

}


public static Color getPixel(int x,int y) throws AWTException{
    Robot rb=new Robot();
    return rb.getPixelColor(x, y);
}   


public static void main(String[] args){
    guiTest frame=new guiTest();    
}

1 个答案:

答案 0 :(得分:1)

问题在于您获取坐标的方式 - e.getX()e.getY() - ,因为它们相对于JFrame(JFrame的左上角是(0) ,0))。

要获取像素的坐标,请使用:

public void mouseClicked(MouseEvent e) {
    Point p = e.getLocationOnScreen();

    System.out.println("Pixel:" + p.x + "," + p.y);
    try {
        System.out.println(getPixel(p.x, p.y));
    } catch (AWTException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

}

[额外]阅读此内容以改进其他内容:Why is my mouse lagging when I run this small mouse hook application?