Retrieve mouse position in JavaFX without event

Tags: , , , ,

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!


Well, you could get mouse coordinates using Robot class. Here is an example. robot =

        int y = robot.getMouseY();
        System.out.println("y point = " + y);
        int x = robot.getMouseX();
        System.out.println("x point= " + x);

It tried it on linux (elementary OS) and it works.

Update: After some googling, I found TestFX which looks like an attempt to implement a prototype for Robot class. Have a look at links given below.

You can also do something like this, to get the coordinates.

public void start(Stage primaryStage) throws Exception {
        GlassRobot robot = new GlassRobotImpl();
        Point2D point = robot.getMouseLocation();
        double x = point.getX();
        double y = point.getY();
        System.out.println("y = " + y);
        System.out.println("x = " + x);
        if(x > 10) {
public static void main(String[] args) {

Source: stackoverflow