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?
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.
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.
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.
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.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With