How to get location of mouse in JavaFX?

后端 未结 3 983
难免孤独
难免孤独 2020-12-05 16:13

I am a beginner in java(fx).
How do you get the mouse location in x and y in JavaFX? I tried using AWT\'s MouseInfo(also imported it), but it\'s not worki

3条回答
  •  日久生厌
    2020-12-05 16:58

    What about using Robot for that purpose ?

    http://docs.oracle.com/javase/1.5.0/docs/api/java/awt/Robot.html

    Using Robots, it is different from posting event to AWT event queue. Events are generated in the native event queue. Actually, with Robot.mouseMove you will not only set mouse position and not only get position.

    For getting mouse position, you may stick to MouseInfo

    import java.awt.MouseInfo;
    // get the mouse's position
    Point p = MouseInfo.getPointerInfo().getLocation();
    

    It's not working: are you with Mac ? Which is your version of JavaFX ? seems to be issues corrected for FX8. For mac only, you may use

    com.sun.glass.ui.Robot robot =
           com.sun.glass.ui.Application.GetApplication().createRobot();
    
    // getPosition of the mouse in Mac
    int x = robot.getMouseX(); 
    int y = robot.getMouseY();
    

提交回复
热议问题