1

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

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

4

1 回答 1

1

Try to check with the position of the image, for eg. if Image position is (X=100, Y=100) and width and height is 100. Then you can check with the current position of the cursor. And get the X position, Y position, width and height from the ImageIcon object. Like -

// 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

So now I can check with-

if((startX <= imgX+imgW && startX >= imgX) && (startY <= imgY+imgH && startY >= imgH))
{
   //On the image
}
else
{
  //Out side of the image
}
于 2013-10-15T05:37:10.630 回答