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();
eltabo
  • 3,749
  • 1
  • 21
  • 33
Ewen W.
  • 199
  • 1
  • 8
  • Basically what you are doing is the same as holding the key down on the keyboard. There is a initial delay and then the key will be repeated until it is released. Can you give a better explanation of what it is you are trying to do...? – MadProgrammer Feb 22 '14 at 20:42

1 Answers1

0

Try:

boolean keepPressing=true;
long startTime = System.currentTimeMillis();
long endTime=null;
long totalTime=null;

while(keepPressing){
    r.keyPress(keyP);
    endTime=System.currentTimeMillis();
    totalTime = endTime - startTime;
    if(totalTime>1999) {
      keepPressing=false;
      r.keyRelease(keyP);
    }
}
ltalhouarne
  • 4,586
  • 2
  • 22
  • 31