Hi all,

I'm wondering if someone can help me. I am trying to write a basic program which involves a square moving across a JPanel in a random direction, and the user needs to click on the square to get a point.

Now I have everything up and running but I cant seem to get the program to work correctly when clicking on the square. Its hit and miss whether the program registers whether the picture has been clicked on. This is the code i'm using to detect whether the square has been hit - can anyone suggest why its not working please!!!

public Rectangle area()
{
    return new Rectangle(getXPos(), getYPos(), boxSize, boxSize);
}
	
public void hit (int mouseX, int mouseY)
{
    Point mousePoint = new Point();
    mousePoint.x = mouseX;
    mousePoint.y = mouseY;
    if(myPicture.area().contains(mousePoint))
    {
         myPicture.hit(); 
    }
}

Recommended Answers

All 6 Replies

simply check inside hit method

System.out.println(mousePoint);
        System.out.println(myPicture.area());

What is myPicture.area()? How did you implement it? Also how did you implement contains()? If you are not sure it is hit, implement the else statement for it and display the value of the mouse location.

When I click in the middle of the square/Rectangle, the System.out returns:

java.awt.Point[x=176,y=227]
java.awt.Rectangle[x=174,y=212,width=20,height=20]

But it doesn't register that the mouse has clicked within the square.

Finally got around this by working out the distance from the mouse click to the centre point of the square. Its not 100% accurate, but it will work for what I am after! I'm still not sure why my original idea didn't work as all outputs showed that it should have been correct!

then without previous jokes,

1/ post here your code, not some code snipped, sucked from some knows url
2/ describe what are you really expected

>I'm still not sure why my original idea didn't work as all outputs showed that it should have been correct!
What you originally posted does look as though it should work, but you haven't provided enough of the rest of your code to determine the problem. As others already mentioned, post more code if you want to investigate it further.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.