如何知道鼠标单击是否超过图形图像java

时间:2013-10-15 05:27:28

标签: java image canvas graphics draw

我想知道是否可以知道当我左键单击我的画布时,它下面是否有一个图像图标,这是必须能够提供这种情况的代码:

 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”)或类似的东西。

1 个答案:

答案 0 :(得分:1)

尝试检查图像的位置,例如。如果图像位置为(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
}