I'm looking to simulate the action of holding a keyboard key down for a short period of time in Java. I would expect the following code to hold down the A key for 5 seconds, but it only presses it once (produces a single 'a', when testing in Notepad). Any idea if I need to use something else, or if I'm just using the awt.Robot class wrong here?
Robot robot = null;
robot = new Robot();
robot.keyPress(KeyEvent.VK_A);
Thread.sleep(5000);
robot.keyRelease(KeyEvent.VK_A);
Just keep pressing?
I think the answer provided by edward will do!!
Thread.sleep() stops the current thread (the thread that is holding down the key) from executing.
If you want it to hold the key down for a given amount of time, maybe you should run it in a parallel Thread.
Here is a suggestion that will get around the Thread.sleep() issue (uses the command pattern so you can create other commands and swap them in and out at will):
There is no keyDown event in java.lang.Robot. I tried this on my computer (testing on a console under linux instead of with notepad) and it worked, producing a string of a's. Perhaps this is just a problem with NotePad?