【问题标题】:Simulate a key held down in Java模拟在 Java 中按住的键
【发布时间】:2010-10-21 12:41:59
【问题描述】:

我希望在 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);

【问题讨论】:

    标签: java awt keypress keyevent


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      一直按吗?

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

      我认为edward提供的答案就可以了!!

      【讨论】:

        【解决方案3】:

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

        【讨论】:

        • 你是对的。在线查看 java 文档说 keyPress 用于按下键,而 keyRelease 用于释放相同的键。我认为问题可能出在 thread.sleep() 上。
        猜你喜欢
        • 1970-01-01
        • 2012-03-12
        • 2011-09-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-02-20
        • 1970-01-01
        相关资源
        最近更新 更多