Thread.sleep () stops the current thread (the thread that holds the key) from executing.
If you want it to hold the key for a given period of time, perhaps you should run it in a parallel thread.
Here is a suggestion that will circumvent the Thread.sleep () problem (uses the command template so that you can create other commands and change them as you see fit):
public class Main { public static void main(String[] args) throws InterruptedException { final RobotCommand pressAKeyCommand = new PressAKeyCommand(); Thread t = new Thread(new Runnable() { public void run() { pressAKeyCommand.execute(); } }); t.start(); Thread.sleep(5000); pressAKeyCommand.stop(); } } class PressAKeyCommand implements RobotCommand { private volatile boolean isContinue = true; public void execute() { try { Robot robot = new Robot(); while (isContinue) { robot.keyPress(KeyEvent.VK_A); } robot.keyRelease(KeyEvent.VK_A); } catch (AWTException ex) {
source share