How to simulate Keyboard press in java

user1247412 picture user1247412 · Aug 31, 2012 · Viewed 7k times · Source

I want to simulate entering a string (can contain any character) in JTextField. I am using new KeyEventData() for that. But I am not able to determine how to handle characters like {, }, ) etc and also how to append a new character to already entered characters.

Answer

trashgod picture trashgod · Aug 31, 2012

You can use Robot for this, as shown in this example. To get {, for example, you'll need to do something like this:

keyPress(KeyEvent.VK_SHIFT);
keyPress(KeyEvent.VK_OPEN_BRACKET);
keyRelease(KeyEvent.VK_OPEN_BRACKET);
keyRelease(KeyEvent.VK_SHIFT);