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

35,646

Solution 1

You need to use Robot

This class is used to generate native system input events for the purposes of test automation, self-running demos, and other applications where control of the mouse and keyboard is needed. The primary purpose of Robot is to facilitate automated testing of Java platform implementations.

Using the class to generate input events differs from posting events to the AWT event queue or AWT components in that the events are generated in the platform's native input queue. For example, Robot.mouseMove will actually move the mouse cursor instead of just generating mouse move events...

Solution 2

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;
}

Solution 3

Robot.mouseMove(x,y)

Solution 4

Check out the Robot class.

Share:
35,646
Abneco
Author by

Abneco

I'm a software developer who strives to solve problems in an efficient and maintainable way. I value lean/agile development practices, simplicity over complexity, and iterative continuous delivery. I'm passionate about keeping up with new languages and technologies, and discussing software development with others. View my code projects on GitHub: https://github.com/dreadwail

Updated on August 04, 2022

Comments

  • Abneco
    Abneco almost 2 years

    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?