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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With