Retrieve mouse position in JavaFX without event

Viewed 2059

I want to retrieve the x and y coordinates of the current mouse position before showing a stage.

So far, the only way I found to get the mouse position in JavaFX is within a MouseEvent, which does not apply to my situation. Furthermore, I found the possibility to retrieve the position via java.awt.MouseInfo. This, however, I think is a bad idea (I use JavaFX not AWT) and, at least in my case, results in a HeadlessException.

Is there an other clean possibility to retrieve the mouse position in JavaFX without getting too hackish (e.g. simulating a MouseEvent just for getting the position)?

Thank you very much!

2 Answers

As @lambad suggested Robot class seems to be a decent way to achieve your need.

I think it is more appropiate to use JavaFX version of Robot which is javafx.scene.robot.Robot.

You could simply use getMousePosition() method which returns the current mouse (x,y) screen coordinates as a javafx.geometry.Point2D.

import javafx.scene.robot.Robot;

Robot robot = new Robot();

System.out.println("X is: " + robot.getMousePosition().getX());
System.out.println("Y is: " + robot.getMousePosition().getY());


Note: Robot objects must be constructed and used on the JavaFX Application Thread.
Related