Scenario: I have one JFrame and JPanel added to that JFrame. on this panel, I have drawn 3 images using:
public void paint(graphics g) {
g.drawImage(img1,100,100,null);
g.drawImage(img2,200,200,null);
g.drawImage(img3,300,300,null);
}
I have implemented MouseListener interface to listen clicks. Now, I want that whenever I click any of these images my output(on command prompt using System.out.println();) should be the image object which I have clicked?
Please explain me is it possible and how?
Well, first of all you are drawing all your images at (0,0), are you sure you want to do that? If you do that is possible that you click a point that belongs to all your images (es, 0,0).
By the way, inside your MouseListener you have this method:
point store the coordinate of your click relative to the component you are listening to.
So what you have to do is simply to check if the point where you click is inside image area. You can do the following:
where x,y are the coordinate where you are drawing your image with drawImage method(0,0 in your case) and image_width, image_height are the dimension of your image.
EDIT:
there is an alternative to the solution I explained above. Like suggested by Hovercraft Full Of Eels you can do the following:
This approach has a great benefit: you don’t have to worry about mouse coordinates because each JLabel has it’s relative mouse listener.
The only one thing that you should consider is the following:
using Component instead of drawing your images, you won’t be able to absolute poisiotion them, but you have to use an appropiate LayoutManager to layout your JLabel.