4

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.

General Grievance
  • 4,555
  • 31
  • 31
  • 45
Lakatos Gyula
  • 3,949
  • 7
  • 35
  • 56

2 Answers2

6
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();
Renato
  • 12,940
  • 3
  • 54
  • 85
  • AWT robot could make troubles, when you launch it in the same VM as JFX app on MacOS, and in such case, one possible option - is to use glass robot. See http://stackoverflow.com/questions/15320915/javafx-screencapture-headless-exception-on-osx. In this case, glass robot is private, but it is not likely to be dangerous. – Alexander Kirov Mar 11 '13 at 09:24
  • Thanks for letting me know about the Mac problem... but I still believe we should point people in the 'standard' direction when they just want to get the mouse's location on the screen easily rather than suggesting this com.sun hack for Macs as a standard. – Renato Mar 11 '13 at 09:35
  • Yes, people should understand and accept, that hach is not an official way. It is just to have a choice for problematic situations. – Alexander Kirov Mar 11 '13 at 11:36
4

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

Alexander Kirov
  • 3,624
  • 1
  • 19
  • 23
  • Possibly, there are could be troubles with one of them on MacOS. So, you will have to exchange them, so, be carefull. I mean, if you will need you solution to be portable, check, that robot is working well on all configs. – Alexander Kirov Jan 06 '13 at 15:08
  • Thanks for the info! Fortunately I have a mac at my workplace. I'll check this out. – Lakatos Gyula Jan 06 '13 at 21:15
  • To advise using JDK internal classes (com.sun.*) is not good practice and this answer is not the best possible way (see my answer). – Renato Mar 11 '13 at 09:16