0

I want to hold down a key for a certain amount of time using the Java Robot. I have read other similar threads, but none of them work. Repeatedly pressing the key will only result in the key not releasing.

Here's my code so far (it does not work since it only presses the key once):

new Thread(new Runnable() {
    public void run() {
        final int keyP = 0; //the key to press

        final int duration = 2000 //2 seconds
        Robot r = null;
        try {
            r = new Robot();
        } catch (AWTException e1) {
            e1.printStackTrace();
        }
        r.keyPress(keyP);
        r.delay(duration); //Thread.sleep does the same thing
        r.keyRelease(keyP);
    }
}).start();
Zong
  • 6,160
  • 5
  • 32
  • 46
Ewen W.
  • 199
  • 1
  • 8
  • What key are you trying to hold (yes, it does make a difference :D). – Anthony Accioly Feb 22 '14 at 19:30
  • I'm trying to hold down any letter key like "s" – Ewen W. Feb 22 '14 at 19:37
  • Use an active loop (terrible busy-waiting anti-pattern, but this is what can be done) and sleep in a different thread: http://stackoverflow.com/questions/784414/simulate-a-key-held-down-in-java – Anthony Accioly Feb 22 '14 at 19:41
  • This is one thing that I've tried, but sadly, it overpresses the key. – Ewen W. Feb 22 '14 at 19:48
  • Define "overpresses", it is working fine for me. – Anthony Accioly Feb 22 '14 at 19:50
  • 1
    Apply the delay before you process the keys – MadProgrammer Feb 22 '14 at 19:52
  • I am working on a program that records your keyboard / mouse actions, and plays them back. Say I initially hold down a key for 2 seconds, when Java robot holds it down for 2 seconds, it will type in a lot more characters. – Ewen W. Feb 22 '14 at 19:53
  • Yes, just use [setAutoDelay](http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html#setAutoDelay(int)) to compensate for the quick succession of key presses (or have a certain [delay](http://docs.oracle.com/javase/7/docs/api/java/awt/Robot.html#delay(int)) inside the loop). – Anthony Accioly Feb 22 '14 at 19:55
  • What is the standard value for autoDelay? – Ewen W. Feb 22 '14 at 19:59
  • Lock at the API source code. For OpenJDK it is `0` ([source](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/7u40-b43/java/awt/Robot.java#72)). – Anthony Accioly Feb 22 '14 at 20:07
  • I mean the standard delay for most computers. Or do they all vary? – Ewen W. Feb 22 '14 at 20:15

0 Answers0