Lucas Baizer
Lucas Baizer

Reputation: 199

Add MouseListener to java.awt.Image

Is there a way I can add a MouseListener to an Image? I took a look at this StackOverflow question, but it didn't really answer how to do this for a java.awt.Image, as there is no Graphics2D Image class. Or at least one I've found.


EDIT:

To clarify, let me try to explain:

With a Ellipse2D, I can say:

if(ellipse2D.contains(mouseX, mouseY) {
    ...do something
}

Is this possible with a java.awt.Image (i.e. image.contains())

Also, this is how the Image gets added to the JPanel:

Image image = item.getIcon().getImage(); //item.getIcon() returns a javax.swing.ImageIcon
g.drawImage(image, imageX, imageY, null);

Upvotes: 1

Views: 379

Answers (1)

JDrost1818
JDrost1818

Reputation: 1126

You can just put the image in a JLabel and add the listener to the JLabel

ImageIcon image = item.getIcon();
JLabel labelWithImage = new JLabel(image);
labelWithImage.addMouseListener(new MouseAdapter() {
    @Override
    public void mouseEntered(MouseEvent e) {
        System.out.println("Mouse Entered Over Image");
    }
});
panel.add(labelWithImage);

Upvotes: 2

Related Questions