43

I want to run a java program and have it simulate keyboard presses. So it could for example, type some text on a focused input box. Is this possible?

Undefined
  • 1,899
  • 6
  • 29
  • 38
  • 3
    The Robot class can do this for you, but if you want to do other more fancy interactions with an outside process, you may wish to use a different language as Java does not get very close to the OS by design. – Hovercraft Full Of Eels Oct 12 '11 at 20:14
  • You mean simulate keyboard presses on an input box of your own program, or from an other application ? – Pierre Sevrain Oct 12 '11 at 20:25

1 Answers1

81

java.awt.Robot might help.

Here's a simple sample code snippet from Java Tips:

try {
        Robot robot = new Robot();

        // Simulate a mouse click
        robot.mousePress(InputEvent.BUTTON1_MASK);
        robot.mouseRelease(InputEvent.BUTTON1_MASK);

        // Simulate a key press
        robot.keyPress(KeyEvent.VK_A);
        robot.keyRelease(KeyEvent.VK_A);

} catch (AWTException e) {
        e.printStackTrace();
}
Nano Taboada
  • 4,148
  • 11
  • 61
  • 89
  • 5
    If you need to achieve this while using JavaFX use FXRobot. The API is quite similar. – Brent Robinson Jan 27 '14 at 06:40
  • 1
    can we write on to another application using robot class? like a text box in another application that is running along with this. – Revanth Kumar May 22 '15 at 07:34
  • How to pess two button simltaneously (like : ctrl+A or SHIFT+A) ? – partho Jun 03 '16 at 13:04
  • 6
    @partho `robot.keyPress(KeyEvent.VK_A);robot.keyPress(KeyEvent.VK_B);robot.keyRelease(KeyEvent.VK_A);robot.keyRelease(KeyEvent.VK_B);` – Daniël van den Berg Aug 24 '16 at 12:36
  • From Robot class javadoc "Note that some platforms require special privileges or extensions to access low-level input control. If the current platform configuration does not allow input control, an AWTException will be thrown when trying to construct Robot objects. For example, X-Window systems will throw the exception if the XTEST 2.2 standard extension is not supported (or not enabled) by the X server." – nyholku Aug 24 '21 at 05:10