我想使用Java机器人按住键一段时间。我已经读过其他类似的线程,但它们都没有用。反复按键只会导致按键无法释放。
到目前为止,这是我的代码(它不起作用,因为它只按一次键):
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();
答案 0 :(得分:0)
尝试:
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);
}
}