Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get mouse position in canvas (java)

I have a canvas inside a window. The window is full screen, but the canvas is not. I need to get the mouse position inside of the canvas, but NOT inside of the window. How do I do this?

I need to get that mouse position several times per second, even if the mouse is not moving, so using MouseMoved listener is not good enough.

Is there any way to get the mouse position in the canvas without having to call any mouselistener?

like image 340
Theriotgames Riot Avatar asked Dec 07 '25 16:12

Theriotgames Riot


2 Answers

Store the mouse position. If it hasn't moved then the position is the same. Then use the mouse moved action listener to update your stored mouse position state as it changes.

like image 177
jzd Avatar answered Dec 09 '25 14:12

jzd


Here's just a simple example about how I'd do it. At first :

  • Get the JFrame's components :

    Component[] components = yourJFrame.getComponents();
    
  • Get your canvas(note : if you added something before adding the canvas,it wont be component 0. Example in Pseudocode add : button1, add:button2, add:canvas - canvas=components[2]):

    Component canvas = components[0];
    
  • Get the mouse's position :

    int mouse_x=MouseInfo.getPointerInfo().getLocation().x-canvas.getLocationOnScreen().x;
    int mouse_y=MouseInfo.getPointerInfo().getLocation().y-canvas.getLocationOnScreen().y;
    

There's absolutely no need for a listener. Feel free to comment if you have any question about this.

like image 43
LMD Avatar answered Dec 09 '25 16:12

LMD



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!