Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I set the position of the mouse in Java?

Tags:

I'm doing some Swing GUI work with Java, and I think my question is fairly straightforward; How does one set the position of the mouse?

like image 281
dreadwail Avatar asked May 31 '10 04:05

dreadwail


People also ask

How do I get my mouse cursor position?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How do I change my mouse pointer in Java?

awt. Cursor class. Create an instance of Cursor using the new operator and pass the cursor type to the Cursor class constructor. We can change Swing's objects ( JLabel , JTextArea , JButton , etc) cursor using the setCursor() method.

Which method are used to get the location of mouse pointer in Swing in Java?

I just ran into this problem in my Java Robot programming, and the short answer is, to get the current mouse cursor location/position, use the getPointerInfo method of the java. awt. MouseInfo class, like this: Point p = MouseInfo.

What is offset in mouse?

offset(). left of the parent div container, and calculate the difference from that to the current X and Y coordinates of the mouse cursor. . offset() always refers to the document and not to the parent of the element.


1 Answers

As others have said, this can be achieved using Robot.mouseMove(x,y). However this solution has a downfall when working in a multi-monitor situation, as the robot works with the coordinate system of the primary screen, unless you specify otherwise.

Here is a solution that allows you to pass any point based global screen coordinates:

public void moveMouse(Point p) {     GraphicsEnvironment ge =          GraphicsEnvironment.getLocalGraphicsEnvironment();     GraphicsDevice[] gs = ge.getScreenDevices();      // Search the devices for the one that draws the specified point.     for (GraphicsDevice device: gs) {          GraphicsConfiguration[] configurations =             device.getConfigurations();         for (GraphicsConfiguration config: configurations) {             Rectangle bounds = config.getBounds();             if(bounds.contains(p)) {                 // Set point to screen coordinates.                 Point b = bounds.getLocation();                  Point s = new Point(p.x - b.x, p.y - b.y);                  try {                     Robot r = new Robot(device);                     r.mouseMove(s.x, s.y);                 } catch (AWTException e) {                     e.printStackTrace();                 }                  return;             }         }     }     // Couldn't move to the point, it may be off screen.     return; } 
like image 139
Daniel Avatar answered Oct 01 '22 11:10

Daniel