Search code examples
javaawtawtrobot

Double click event using Robot class in awt package


I have already seen lot of threads regarding double click events using MouseEvent. But that is not what I am looking for. I recently started using Robot class and came across few functions of mouse like mouseMove(x,y), mouseRelease(int buttons).

Robot class provides mousePress(int button); function as well. I have tried this.

Robot robot = new Robot();
robot.mouseMove(305, 450);
robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);

But this is a single click event. What I am trying to achieve is the double click event using Robot class. Is it possible to achieve that ? If so. then how ?


Solution

  • The Robot class doesn't provide a way of double-clicking. You'll have to implement that yourself. Think about what a double-click really is, it's two clicks in quick succession. (Depending on your OS settings, the required time between clicks might vary.)

    So you really just need to click twice really quickly:

    Robot robot = new Robot();
    robot.mouseMove(305, 450);
    // first click
    robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    // second click
    robot.mousePress(InputEvent.BUTTON1_DOWN_MASK);
    robot.mouseRelease(InputEvent.BUTTON1_DOWN_MASK);
    

    You might also want to add a few milliseconds of delay between the two clicks, as some things might not respond well to too-fast clicks.