简体   繁体   English

模拟用Java按下的键

[英]Simulate a key held down in Java

I'm looking to simulate the action of holding a keyboard key down for a short period of time in Java. 我正在寻找模拟在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). 我希望下面的代码按住A键5秒钟,但是只按一次它(在记事本中测试时会产生一个“ a”)。 Any idea if I need to use something else, or if I'm just using the awt.Robot class wrong here? 我是否需要使用其他东西,或者我在这里使用awt.Robot类错了吗?

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. Thread.sleep()阻止当前线程(按住键的线程)执行。

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): 这是一个解决Thread.sleep()问题的建议(使用命令模式,以便您可以创建其他命令并随意交换它们):

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

Just keep pressing? 只是一直按?

import java.awt.Robot;
import java.awt.event.KeyEvent;

public class PressAndHold { 
    public static void main( String [] args ) throws Exception { 
        Robot robot = new Robot();
        for( int i = 0 ; i < 10; i++ ) {
            robot.keyPress( KeyEvent.VK_A );
        }
    }
}

I think the answer provided by edward will do!! 我认为爱德华提供的答案会的!

There is no keyDown event in java.lang.Robot. java.lang.Robot中没有keyDown事件。 I tried this on my computer (testing on a console under linux instead of with notepad) and it worked, producing a string of a's. 我在我的计算机上尝试了此操作(在Linux下而不是使用记事本在控制台上进行测试),它可以正常工作,并产生一个字符串a。 Perhaps this is just a problem with NotePad? 也许这只是NotePad的问题?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM