java - java 如何知道鼠标点击是否在图形图像上

标签 java image canvas graphics draw

我想知道是否可以知道当我左键单击 Canvas 时,其下方是否有一个图像图标,这是必须能够处理这种情况的代码:

 public void mousePressed(MouseEvent evt) {
    if (!labelSelected){

    // This is called by the system when the user presses the mouse button.
    // Record the location at which the mouse was pressed.  This location
    // is one endpoint of the line that will be drawn when the mouse is
    // released.  This method is part of the MouseLister interface.
    startX = evt.getX();
    startY = evt.getY();
    prevX = startX;
    prevY = startY;
    dragging = true;
    Random ran = new Random();
    int x = ran.nextInt(10);
    currentColorIndex = x;
    gc = getGraphics();  // Get a graphics context for use while drawing.
    gc.setColor(colorList[currentColorIndex]);
    gc.setXORMode(getBackground());
    gc.drawLine(startX, startY, prevX, prevY);
    }
}

但在绘制线条之前,我想确保鼠标按下在图形图像上,例如 if (evt.getsource() == "Graphics ICON") 或类似的东西。

最佳答案

尝试检查图像的位置,例如。如果图像位置为(X=100,Y=100)且宽度和高度为100。那么您可以检查光标的当前位置。并从 ImageIcon 对象中获取 X 位置、Y 位置、宽度和高度。喜欢 -

// imgX has the position of Image in X direction
// imgY has the position of Image in Y direction
// imgW has the width of image
// imgH has the height of image

现在我可以检查-

if((startX <= imgX+imgW && startX >= imgX) && (startY <= imgY+imgH && startY >= imgH))
{
   //On the image
}
else
{
  //Out side of the image
}

关于java - java 如何知道鼠标点击是否在图形图像上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19373880/

相关文章:

java - 尝试在空对象引用上调用虚拟方法 'java.lang.String android.net.Uri.toString()'

WPF - 如何对裁剪后的图像应用效果?

javascript - 为什么这个脚本在 Javascript 中会出现延迟?

javascript - Arbor js - 将鼠标移到节点上时将节点 ID 显示为文本

html - 与其他图像相比图像的响应尺寸

javascript - 在 HTML5 Canvas 中轻松使图像跟随鼠标

JavaFX LineChart 图例样式

使用 Maven 将 Java 应用程序部署到 heroku 失败

java - 使用 Java 和 Oauth2 对 Google Drive 进行身份验证

image - 如何解决VB6中的运行时错误 '429 : Activex component can' t创建对象?