4

I am using Java to generate a mouse press using the Robot class:

robot.mousePress(InputEvent.BUTTON1_MASK);
robot.mouseRelease(InputEvent.BUTTON1_MASK);

However, I want the Robot to press the button for a certain period of time. How can I achieve this?

Jason Plank
  • 2,336
  • 5
  • 31
  • 40
Neutralise
  • 189
  • 2
  • 2
  • 6

2 Answers2

12

Just sleep a bit between the two actions (specified in milliseconds):

  1. Thread.sleep(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    try { Thread.sleep(1000); } catch(Exception e) {} // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    
  2. Robot.delay(long millis);

    robot.mousePress(InputEvent.BUTTON1_MASK);
    robot.delay(1000); // Click one second
    robot.mouseRelease(InputEvent.BUTTON1_MASK);
    
Martijn Courteaux
  • 67,591
  • 47
  • 198
  • 287
  • Don't use `Robot.delay(long)`, - it's broken. Caused me a lot of pain in past. This library method eats interruptions. I.e. it doesn't reset the flag in catch block and you can't write any sensible cancellable by interruption tasks, that use `delay` for that reason. Use `TimeUnit.MILLISECONDS.sleep(long timeout)` instead and always finish `catch (InterruptedException e)` block with the call "Thread.currentThread().interrupt();" to propagate the interruption flag to the owner of the tread (e.g. some standard `ExecutorService` created with one of the static methods of `Executors`). – vitrums Jan 03 '21 at 12:28
0

I did that, it's simple: when you detect the mouse is pressed, you save the System.currentTimeMillis(). When you detect the mouse is released, you just check how long it was pressed.

If you want the action to be made after a certain amount of time, even if the mouse is still pressed, you start a thread that lives the desired amount of time when pressed and you interrupt it when releasing. If the thread isn't interrupted in the amount of time you wanted, the action will be performed.

SteeveDroz
  • 6,006
  • 6
  • 33
  • 65