Search code examples
javaswingawtrobot

Type a String using java.awt.Robot


I already know how to use java.awt.Robot to type a single character using keyPress, as seen below. How can I simply enter a whole pre-defined String value at once into a textbox?

robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);
robot.keyPress(KeyEvent.VK_1);  
// instead, enter String x = "111"

Solution

  • Common solution is to use the clipboard:

    String text = "Hello World";
    StringSelection stringSelection = new StringSelection(text);
    Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
    clipboard.setContents(stringSelection, stringSelection);
    
    Robot robot = new Robot();
    robot.keyPress(KeyEvent.VK_CONTROL);
    robot.keyPress(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_V);
    robot.keyRelease(KeyEvent.VK_CONTROL);