Lakatos Gyula
Lakatos Gyula

Reputation: 4160

JavaFX 2 set/get cursor position

How can I set/get the cursor's position in JavaFX 2?

I tired googling the answer but found nothing useful. All I can do is setting the cursor's style.

Upvotes: 4

Views: 7542

Answers (2)

Renato
Renato

Reputation: 13720

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

import java.awt.Robot;
// set the mouse position
new Robot().mouseMove( x, y );

PS. DO NOT USE com.sun.* classes (unless you're using Mac, see below).

PS2. Due to a JavaFX issue which seems will be fixed in JavaFX8, you cannot use java.awt classes in Mac, so as pointed out by Alexander Kirov, in Mac you still need to use the com.sun classes like so:

// workaround for Mac only
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();

Upvotes: 6

Alexander Kirov
Alexander Kirov

Reputation: 3654

You can use robot for that purpose:

AWT robot:

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

or glass robot:

com.sun.glass.ui.Robot; which could be created with: com.sun.glass.ui.Application.GetApplication().createRobot();

To get the cursor position, see other post for this question about java.awt.MouseInfo

Upvotes: 4

Related Questions