Simulate a key held down in Java

前端 未结 3 1500
暗喜
暗喜 2020-12-03 19:50

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

相关标签:
3条回答
  • 2020-12-03 20:14

    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!!

    0 讨论(0)
  • 2020-12-03 20:24

    There is no keyDown event in java.lang.Robot. 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. Perhaps this is just a problem with NotePad?

    0 讨论(0)
  • 2020-12-03 20:35

    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();
    }
    
    0 讨论(0)
提交回复
热议问题