模拟的Java按住关键 [英] Simulate a key held down in Java
问题描述
我期待模拟拿着键盘按键下来的时间在Java中短期内的操作。我希望下面的code按住A键5秒,但它只是presses一次(产生一个A,在记事本进行测试时)。任何想法,如果我需要使用别的东西,或者如果我只是用awt.Robot类错在这里?
机器人机器人= NULL;
机器人=新机器人();
robot.key preSS(KeyEvent.VK_A);
视频下载(5000);
robot.keyRelease(KeyEvent.VK_A);
Thread.sleep()方法从执行停止当前线程(即按住键的线程)。
如果你想让它按住键为给定时间内,也许你应该在并行线程中运行它。
下面是一个建议,将让周围的Thread.sleep()方法的问题(使用命令模式,所以你可以创建其他的命令和随意交换他们进出):
公共类主要{公共静态无效的主要(字串[] args)抛出InterruptedException的{
最后RobotCommand pressAKeyCommand =新的pressAKeyCommand();
线程t =新主题(新的Runnable(){ 公共无效的run(){
pressAKeyCommand.execute();
}
});
t.start();
视频下载(5000);
pressAKeyCommand.stop(); }
}类pressAKeyCommand实现RobotCommand {私人挥发性布尔isContinue = TRUE;公共无效的execute(){
尝试{
机器人机器人=新的机器人();
而(isContinue){
robot.key preSS(KeyEvent.VK_A);
}
robot.keyRelease(KeyEvent.VK_A);
}赶上(前的AWTException){
//使用异常的东西
}
} 公共无效停止(){
isContinue = FALSE;
}
}接口RobotCommand { 无效的execute(); 空隙停止();
}
I'm looking to simulate the action of holding a keyboard key down for a short period of time in Java. I would expect the following code to hold down the A key for 5 seconds, but it only presses it once (produces a single 'a', when testing in Notepad). Any idea if I need to use something else, or if I'm just using the awt.Robot class wrong here?
Robot robot = null;
robot = new Robot();
robot.keyPress(KeyEvent.VK_A);
Thread.sleep(5000);
robot.keyRelease(KeyEvent.VK_A);
Thread.sleep() stops the current thread (the thread that is holding down the key) from executing.
If you want it to hold the key down for a given amount of time, maybe you should run it in a parallel Thread.
Here is a suggestion that will get around the Thread.sleep() issue (uses the command pattern so you can create other commands and swap them in and out at will):
public class Main {
public static void main(String[] args) throws InterruptedException {
final RobotCommand pressAKeyCommand = new PressAKeyCommand();
Thread t = new Thread(new Runnable() {
public void run() {
pressAKeyCommand.execute();
}
});
t.start();
Thread.sleep(5000);
pressAKeyCommand.stop();
}
}
class PressAKeyCommand implements RobotCommand {
private volatile boolean isContinue = true;
public void execute() {
try {
Robot robot = new Robot();
while (isContinue) {
robot.keyPress(KeyEvent.VK_A);
}
robot.keyRelease(KeyEvent.VK_A);
} catch (AWTException ex) {
// Do something with Exception
}
}
public void stop() {
isContinue = false;
}
}
interface RobotCommand {
void execute();
void stop();
}
这篇关于模拟的Java按住关键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!