Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 877
Lakatos Gyula Avatar asked Dec 26 '22 11:12

Lakatos Gyula


2 Answers

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();
like image 87
Renato Avatar answered Dec 29 '22 02:12

Renato


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

like image 40
Alexander Kirov Avatar answered Dec 29 '22 01:12

Alexander Kirov