4

I want to get the position of my mouse relative to the frame when I click a shortcut:

@Override
public void handle(KeyEvent keyEvent) {
    if (keyEvent.isShortcutDown()) {
        if (keyEvent.getCode() == KeyCode.P) {
            //Code Here
        }
    }
}
sKhan
  • 9,694
  • 16
  • 55
  • 53
JBaoz
  • 180
  • 10
  • 3
    Have a look [here](http://stackoverflow.com/questions/16635514/how-to-get-location-of-mouse-in-javafx) . Basically - you can have a `MouseMoved` listener (on your root node) that keeps track of the current position in some member field(s). Don't know if that's the optimal way though, so you may want to wait for expert opinion :) – Itai Mar 03 '16 at 07:43
  • @sillyfly in my opinion, that would be the best option too. Keep track of the mouse through mouse listener – Steven Mar 03 '16 at 07:48
  • @Steven: He probably meant, that this way mouse position will be tracked always, and it would be much better if it would be tracked only when key is pressed. – T.G Mar 03 '16 at 07:55
  • @T.G that's what I meant. Have a global variable keeping track of Mouse Point at all times, and just recall that when a key is pressed. Seems like the only way IMO. – Steven Mar 03 '16 at 09:12

2 Answers2

0

When the KeyEvent fires, just get the pointer location using MouseInfo.

@Override
public void handle(KeyEvent keyEvent) {
if (keyEvent.isShortcutDown()) {
    if (keyEvent.getCode() == KeyCode.P) {
        //Code Here
        Point mouseLoc = MouseInfo.getPointerInfo().getLocation();
    }
}

If you want to continuously track the mouse location, you should use a MouseMoved listener.

Austin
  • 8,018
  • 2
  • 31
  • 37
  • `MouseInfo` is an awt class, not Javafx. Pretty sure it won't work, or would cause problems. – Itai Mar 03 '16 at 08:03
  • Although `MouseInfo` is an awt class, this approach works exactly as expected: the controller handles it just like any other method call. – Austin Mar 03 '16 at 08:08
  • Apparently it can cause problems on osx - https://bugs.eclipse.org/bugs/show_bug.cgi?id=449942 . If it works then I guess it's fine, but some may argue it's inadvisable (see jewelsea's note in the answer I linked on the original question) – Itai Mar 03 '16 at 08:35
  • 1
    I don't think this works because it finds the mouse position relative to the entire screen instead of just the JavaFX frame. – JBaoz Mar 03 '16 at 11:19
0

Hey here from five years in the future. Since JavaFX still doesn't have this feature for some reason, my solution was to subtract the X/Y position of the cursor's position on the screen (java.awt.MouseInfo) from the X/Y position of the stage. As an example for Y:

  MouseInfo.getPointerInfo().getLocation().getY() - stage.getY()

It's not perfect, you'll have to optimize it a bit, but it's an actual solution (the first guy who answered seems to think the screen equals the stage...)

Krusty the Clown
  • 517
  • 6
  • 24