Yuan  Kai
Yuan Kai

Reputation: 31

How to get mouse location relative to the JPanel on every frame

Now I'm doing this

mouseX = MouseInfo.getPointerInfo().getLocation().x;

but this doesn't work anymore if I move the JFrame.

Also I need the mouse position every time I move my mouse because I want to drag stuff in my game thus mouse event won't work.

How do I get the mouse location relative to the JPanel every frame?


Edit 1: Ok I have figured it out. I'm take the mouse location subtract the jframe location on screen then I get the mouse position on jpanel

Upvotes: 1

Views: 2626

Answers (2)

Callum Rae
Callum Rae

Reputation: 53

Let's say you created a JPanel like so:

JPanel myJPanel = new JPanel;

you can use:

myJPanel.getMousePosition().x and myJPanel.getMousePosition().y to get the x and y coordinates of the mouse respectively. These will be relative to the top right corner of your JPanel.

Be careful, if your mouse isn't inside the panel, or the panel isn't visible, this will return a null value, so, if you ever want to call these functions, wrap the code that uses them inside a try like so:

try{
    [insert code that uses myJPanel.getMousePosition().x/y here, if your mouse isn't inside the JPanel or the JPanel isn't visible, the code here will not be executed]
   }catch(NullPointerException e) {[if your mouse isn't inside the JPanel or the JPanel isn't visible, code placed here will be executed]}

This will stop your code throwing errors in cases where your mouse is outside the bounds of the JPanel or your JPanel isn't visible.

This can work well if you only ever intend to execute the code when your mouse is inside a visible JPanel, but otherwise, I would stick to other methods to get the mouse coordinates.

It's useful for doing things such as clicking on objects inside your JPanel, but it does have limitations.

Upvotes: 0

qlown
qlown

Reputation: 527

Question is "How to get mouse location relative to the JPanel on every frame".

I take from this you don't necessarily have mouse events for each frame, so you have to poll mouse position (relative to screen), and compute the relative position (relative to your JPanel).

All in all, it makes me think you want this:

Point p = MouseInfo.getPointerInfo().getLocation();
SwingUtilities.convertPointFromScreen(p, yourJPanel);
// Then use 'p', which was modified by method call above

Upvotes: 6

Related Questions