How to make Java Robot hold down a key?

混江龙づ霸主 提交于 2019-12-12 05:58:48

问题


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


来源:https://stackoverflow.com/questions/21958633/how-to-make-java-robot-hold-down-a-key

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!