如何使Java Robot按住一个键? [英] How to make Java Robot hold down a key?
本文介绍了如何使Java Robot按住一个键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想使用Java机器人按住某个键一段时间.我读过其他类似的主题,但是它们都不起作用.反复按该键只会导致该键无法释放.
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();
推荐答案
尝试:
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);
}
}
这篇关于如何使Java Robot按住一个键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文