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

dreadwail picture dreadwail · May 31, 2010 · Viewed 33k times · Source

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?

Answer

Daniel picture Daniel · May 19, 2012

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