Getting mouse's position returns position without window bar

51 views Asked by At

I am making a little box you can drag around on a JFrame. I use normal MouseListeners (MouseListener and MouseMotionListener), and when I get the position, I think it includes the window bar at the top and adds that to the Y value. Same with the X value and the side of the window. This results in the box moving to a location that is to the bottom-right of your mouse. How do I fix this?

1

There are 1 answers

0
Matthew Rowlands On

I think you are saying that the boxes top left corners location is equal to the mouses location? In which case, you should take away half of the size of the box on the x and y axis.

The x value is the very left of the box, and the y value is the very top of the box. The size is (size) more pixels to the right and below.

Rectangle r = new Rectange(mouseX, mouseY, sizex, sizey);

drawBox(r.x - r.width/2, r.y - r.height/2, r.width, r.height);