1

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

4

1 回答 1

5

MouseListener像往常一样将 a 添加到窗格中。

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-10-15T10:35:03.670 回答