Reputation: 1541
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!
Upvotes: 4
Views: 2990
Reputation: 2004
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());
Upvotes: 1
Reputation: 1066
Well, you could get mouse coordinates using Robot class. Here is an example.
com.sun.glass.ui.Robot robot =
com.sun.glass.ui.Application.GetApplication().createRobot();
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. https://github.com/TestFX/Robot http://mail.openjdk.java.net/pipermail/openjfx-dev/2015-December/018412.html
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) {
primaryStage.show();
}
public static void main(String[] args) {
launch(args);
}
Upvotes: 5