File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Swing / AWT / SWT and the fly likes clicked Image Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Swing / AWT / SWT
Bookmark "clicked Image" Watch "clicked Image" New topic

clicked Image

kenji jonathan

Joined: Oct 07, 2011
Posts: 4

Friends, I want to ask how to make an image with graphics2d added with mouseListener.

I want to make an image, if it is clicked, something occur. here is my code :

how to make this image clickable?..thanks
Maneesh Godbole
Saloon Keeper

Joined: Jul 26, 2007
Posts: 10832

1) You know the Rectangle which displays the image
2) MouseEvent has the capability to provide you the x and y co-ordinates of the mouse click
3) Rectangle can tell if if a particular Point is inside/outside that rectangle

[How to ask questions] [Donate a pint, save a life!] [Onff-turn it on!]
Randall Twede
Ranch Hand

Joined: Oct 21, 2000
Posts: 4351

it is pretty simple really. one of your classes(usually the one you are drawing on) needs to implement MouseListener(or extend MouseAdapter) and override the mouseClicked method. here is an example.

i didnt use mouseClicked in this example but it should give you the idea. you have to implement all the methods of MouseListener even if they do nothing.

i forgot to mention in your constructor you have to add the MouseListener. in the example it looks like this:

another suggestion is to use mousePressed instead of mouseClicked.

Visit my download page
I agree. Here's the link:
subject: clicked Image
It's not a secret anymore!