java - adding action listener to an image -
i insert image jpanel
. write code.
public void paint(graphics g) { img1=gettoolkit().getimage("/users/boaz/desktop/piece.png"); g.drawimage(img1, 200, 200,null); }
i want add action listener picture, not have addactionlistener()
method. how can without putting image in button or label?
there few options.
use mouselistener
directly in jpanel
a simple dirty way add mouselistener
directly jpanel
in overrode paintcomponent
method, , implement mouseclicked
method checks if region image exists has been clicked.
an example along line of:
class imageshowingpanel extends jpanel { // image display private image img; // mouselistener handles click, etc. private mouselistener listener = new mouseadapter() { public void mouseclicked(mouseevent e) { // should done when image clicked. // you'll need implement checks see region // click occurred within bounds of `img` } } // instantiate panel , perform initialization imageshowingpanel() { addmouselistener(listener); img = ... // load image. } public void paintcomponent(graphics g) { g.drawimage(img, 0, 0, null); } }
note: actionlistener
can't added jpanel
, jpanel
not lend create considered "actions".
create jcomponent
display image, , add mouselistener
a better way make new subclass of jcomponent
sole purpose display image. jcomponent
should size size of image, click part of jcomponent
considered click on image. again, create mouselistener
in jcomponent
in order capture click.
class imageshowingcomponent extends jcomponent { // image display private image img; // mouselistener handles click, etc. private mouselistener listener = new mouseadapter() { public void mouseclicked(mouseevent e) { // should done when image clicked. } } // instantiate panel , perform initialization imageshowingcomponent() { addmouselistener(listener); img = ... // load image. } public void paintcomponent(graphics g) { g.drawimage(img, 0, 0, null); } // method override tell layoutmanager how large component // should be. we'll want make component same size `img`. public dimension getpreferredsize() { return new dimension(img.getwidth(), img.getheight()); } }
Comments
Post a Comment