如何将鼠标监听器添加到JPanel图像?

时间:2012-10-15 10:20:24

标签: java swing jpanel mouse-listeners swingutilities

我在JPanel上使用以下代码绘制了BufferedImage。

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);
    }
}

如何向该图像添加鼠标单击侦听器?另外,我想得到图像的点击坐标,而不是JPanel。

1 个答案:

答案 0 :(得分:5)

按正常情况将MouseListener添加到窗格。

mouseClicked方法中检查Point是否在图片的矩形内...

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...
        }
    }
}