swing - Get Pixel Color on screen Java? -
hello trying color of particular pixel on jframe.
this code. frame red.
the problem having when click frame should return me rgb color red (255,0,0) when click @ different points rgb color white (255,255,255) problem in 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(); }
the problem way getting coordinates - e.getx()
, e.gety()
-, because relative jframe
(the up-left corner of jframe (0,0)).
to coordinates of 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 improve other things: why mouse lagging when run small mouse hook application?
Comments
Post a Comment