Tuesday, November 6, 2007

move the swing-ing mouse

Yesterday i came across the problem of moving the mouse pointer programatically from within a java swing programm. It was not hard to find how to move the mouse with the Robot class.

new Robot().mouseMove(x, y);

But moving it that way is relative to the screen display and not to the focused awt component. The solution ? Very easy, you just have to know the right utility class ;)

Here's a complete little class:

import java.awt.AWTException;
import java.awt.Component;
import java.awt.Point;
import java.awt.Robot;
import javax.swing.SwingUtilities;

public class MouseMove {
    private Robot _robot;

    public MouseMove() {
        try {
            _robot = new Robot();
        catch (AWTException e) {
            throw new RuntimeException(e);

    public void moveMouse(Point pointOnComponent, Component component) {
        Point pointOnScreen = (PointpointOnComponent.clone();
        SwingUtilities.convertPointToScreen(pointOnScreen, component);
        _robot.mouseMove(pointOnScreen.x, pointOnScreen.y);