我在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。
答案 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...
}
}
}