How to make Java Robot hold down a key?

2019-09-15 00:40发布

问题:

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();

回答1:

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);
    }
}