Reputation: 72
I wanted to know if it is possible to know if when I left click my canvas there is an image icon under it, this is the code that must be able to hand that case:
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);
}
}
but before drawing my line I want to make sure that the mouse is pressed over an graphics image, something like if (evt.getsource() == "Graphics ICON") or something like that.
Upvotes: 1
Views: 1823
Reputation: 2265
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
}
Upvotes: 1