模拟Java中的一个键

我希望模拟在Java中短时间内按住键盘键的动作。 我希望下面的代码按住A键5秒钟,但它只按一次(在记事本中测试时产生一个’a’)。 知道我是否需要使用其他东西,或者我只是在这里使用awt.Robot类错了?

Robot robot = null; robot = new Robot(); robot.keyPress(KeyEvent.VK_A); Thread.sleep(5000); robot.keyRelease(KeyEvent.VK_A); 

Thread.sleep()停止执行当前线程(按住键的线程)。

如果你想让它按住键一段时间,也许你应该在并行线程中运行它。

这是一个解决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(); } 

只是按下?

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

我想爱德华提供的答案会做!!

java.lang.Robot中没有keyDown事件。 我在我的计算机上尝试过这个(在linux下的控制台上测试,而不是用记事本测试)并且它有效,产生了一串字符串。 也许这只是NotePad的一个问题?