How to add mouse listener to a JPanel image?

2.1k views Asked by At

I have painted a BufferedImage on a JPanel with the following code.

protected void paintComponent(Graphics g) {
    if (image != null) {
        super.paintComponent(g);

        Graphics2D g2 = (Graphics2D) g;

        double x = (getWidth() - scale * imageWidth) / 2;
        double y = (getHeight() - scale * imageHeight) / 2;
        AffineTransform at = AffineTransform.getTranslateInstance(x, y);
        at.scale(scale, scale);
        g2.drawRenderedImage(image, at);
    }
}

How can I add a mouse click listener to that image? Additionally, I want to get the click coordinate of the image, not the JPanel.

1

There are 1 answers

0
MadProgrammer On

Add a MouseListener to the pane as per normal.

In the mouseClicked method check to see if the Point is within the rectangle of the image...

public void mouseClicked(MouseEvent evt) {

    if (image != null) {
        double width = scale * imageWidth;
        double height = scale * imageHeight;
        double x = (getWidth() - width) / 2;
        double y = (getHeight() - height) / 2;
        Rectangle2D.Double bounds = new Rectangle2D.Double(x, y, width, height);
        if (bounds.contains(evt.getPoint()) {
          // You clicked me...
        }
    }
}