问题
Hello I am trying to get the color of a particular pixel on my JFrame.
This is my code. My frame is red.
The problem I am having is when I click the Frame it should return me the RGB color for red that is (255,0,0) but when I click at different points i sometimes get the RGB color for white (255,255,255) what is the problem in my code guys?
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:
The problem is the way you are getting the coordinates - e.getX()
and e.getY()
-, because they are relative to the JFrame
(the up-left corner of the JFrame is (0,0)).
To get the coordinates of the pixel, use:
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();
}
}
[Extra] read this to improve other things: Why is my mouse lagging when I run this small mouse hook application?
来源:https://stackoverflow.com/questions/22217148/get-pixel-color-on-screen-java