Type a String using java.awt.Robot

user1196937 picture user1196937 · Apr 16, 2015 · Viewed 31.3k times · Source

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"

Answer

Eng.Fouad picture Eng.Fouad · Apr 16, 2015

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