How to simulate Keyboard press in java

耗尽温柔 提交于 2019-12-23 10:06:08

问题


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.


回答1:


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



回答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 =]




回答3:


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



来源:https://stackoverflow.com/questions/12222018/how-to-simulate-keyboard-press-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!