【问题标题】:How to add mouse listener to a JPanel image?如何将鼠标侦听器添加到 JPanel 图像?
【发布时间】:2012-10-15 18:35:03
【问题描述】:

我使用以下代码在 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。

【问题讨论】:

  • 首先,无论image的状态如何,请确保您始终调用super.paintComponent
  • 如需尽快获得更好的帮助,请发帖SSCCE
  • 请看看这个example

标签: java swing jpanel mouse-listeners swingutilities


【解决方案1】:

像往常一样将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...
        }
    }
}

【讨论】:

    猜你喜欢
    • 2012-07-19
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2014-08-26
    • 1970-01-01
    • 2012-02-28
    • 1970-01-01
    • 2012-08-01
    相关资源
    最近更新 更多