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

Robot.mouseMove(x,y)


Check out the Robot class.


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...


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