Java fillRect on coordinates and coordinates of a mouse point

I encountered this problem in the game I am writing, but reproduced the problem on a separate bank, consisting only of a frame, a panel and a mouse movement listener.

The problem is that I draw a rectangle - for example, in x:512, y:384 (48x48) .

Using the mouse's motion listener on the frame, it always reports about the Y axis about 25 pixels less. Therefore, when the coordinate of the rectangle should be x:512, y:384 , the mouse listener reports x:512, y:409 .

Theoretically, I can just add the difference to the Y mouse, but I need to understand why this is happening.

Full code for three example classes

+4
source share
2 answers

it always reports about y axis about 25 pixels smaller

You may have added MouseListener to the frame instead of the panel.

You will draw your rectangles on the panel, but the panel is (on my OS) 30 pixels down from the top of the frame so that your coordinates do not match. The value of X should also be equal to the width of the frame border.

Try adding a listener to the panel.

+3
source

The origin of Frame and Board is different. The origin of the Board is (0, 25) of Frame .

Got it now?

Not a good image. Firstly, the screenshot will not show the cursor, so I drew it. Secondly, I did not place the cursor exactly on (0, 25) , but only around it.

+1
source

Source: https://habr.com/ru/post/1483244/


All Articles