6

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.

mKorbel
  • 109,525
  • 20
  • 134
  • 319
user1247412
  • 647
  • 7
  • 16
  • 29

3 Answers3

5

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);
Community
  • 1
  • 1
trashgod
  • 203,806
  • 29
  • 246
  • 1,045
2

This might be helpful for emulating keyevents: How to simulate keyboard presses in java?

For left and right brace, KeyEvent.VK_BRACELEFT and KeyEvent.VK_BRACERIGHT http://docs.oracle.com/javase/7/docs/api/java/awt/event/KeyEvent.html#VK_BRACELEFT

Hope this helps =]

Community
  • 1
  • 1
corgichu
  • 2,580
  • 3
  • 32
  • 46
  • @ cskoala: I am not able to determine which key to press at runtime and how to append key character to already typed string. – user1247412 Aug 31 '12 at 20:31
  • Sorry, what exactly are you trying to do? I thought you just wanted to simulate entering a string? Are you waiting for user input at runtime or are you putting which keys to press in your code? – corgichu Aug 31 '12 at 20:34
  • I take an input from string. Then I want to simulate that value to be typed in a JTextField. – user1247412 Aug 31 '12 at 20:41
  • oh okay, so can't you parse the String character by character then have a switch statement with each possible character and simulate the key presses that way? – corgichu Aug 31 '12 at 20:48
  • do you think that'll work for you? if so and you're confused, I can provide a small sample. – corgichu Aug 31 '12 at 20:48
  • Actually I got your point, only thing I am worried is that will be a lengthy code. – user1247412 Aug 31 '12 at 21:31
  • Yeah, it would be pretty lengthy, but a switch statement would be the only way to differentiate which keyPress to simulate since you have to use a different KeyEvent.VK for each different character. – corgichu Aug 31 '12 at 21:53
1

check VK_BRACELEFT, VK_BRACERIGHT, VK_RIGHT_PARENTHESIS and VK_LEFT_PARENTHESIS for handling those characters.

For the appending the character, you might suppose building the list of characters or building the string.

edit: for getting the character value from the keyevent try KeyEvent.getKeyChar()

lebryant
  • 351
  • 2
  • 18