I am writing a basic program that asks the user to type in a String, and I am trying to use a Robot (from java.awt.Robot
)that will type this message back into another document after a delay. The Problem I have now is that I need to convert whatever I get from message.charAt(i)
to a KeyEvent.VK_[insert Char]
KeyCode. Is there a better way to do what I am trying to do? I suppose I could always just have a massive switch statement that gets the appropriate KeyCode but I was hoping there would be a more elegant way. My first thought, having done python for awhile, was to make a string "KeyEvent.VK_" + message.charAt(i)
and convert that to code somehow, but I think the only way to do that is using Reflection which is discouraged.
Asked
Active
Viewed 4.2k times
17

Ryan
- 416
- 1
- 6
- 14
-
Ah, this should be simpler then it is. The larger problem you will have is that different keyboard layouts will change what combination of keys are required to include "extended" key strokes (like `shift+...`). The other problem is, that a "A" and "a" are the same virtual key, what disginstushes them from each other is the addition of the `Shift` key. Take a look at [this](http://stackoverflow.com/questions/14572270/how-can-i-perfectly-simulate-keyevents/14615814#14615814) for some idea of the problems your about to face. – MadProgrammer Mar 06 '13 at 23:36
4 Answers
27
If I have a unicode character and all I want is to know the keystroke for it, then I use
int keyCode = java.awt.event.KeyEvent.getExtendedKeyCodeForChar(charCode);
I've never needed another, more complicated way to do this.

Steve K
- 4,863
- 2
- 32
- 41
-
2
-
It's Java7... but you can easily use it to run through all the possible values and create, for instance, a Properties MAP you could use in previous versions. – Steve K Dec 16 '13 at 04:26
-
1@phreakhead, be sure you import the correct KeyEvent class. You want `java.awt.event.KeyEvent`. When I first tried this method my IDE picked up another one packaged with Java! – Jason Nov 01 '17 at 22:15
-
There is a problem with colon `:`. `robot.keyPress(KeyEvent.getExtendedKeyCodeForChar(text.charAt(i)));` this line throws `IllegalArgumentException` when char occur to be `:` – Pochmurnik Sep 30 '19 at 12:28
-
For someone that will search for it, it also doesn't work for '@'. This is because there is no such a key on keyboard like `:` or `@`; – Pochmurnik Sep 30 '19 at 13:16
-
@Pochmurnik To get those symbols to work, you need the robot to press the shift key as well. If you want to type a `!` using the robot, you need, `Robot.keyPress(KeyEvent.VK_SHIFT)` and `Robot.keyPress(KeyEvent.VK_1)` – Kcits970 Mar 09 '20 at 15:29
-
It's now obvious to me, I just commented to make it obvious to future searchers. Ty anyway. – Pochmurnik Mar 10 '20 at 07:59
14
You could work something out with this:
KeyStroke ks = KeyStroke.getKeyStroke('k', 0);
System.out.println(ks.getKeyCode());
or just use this:
private void writeString(String s) {
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
if (Character.isUpperCase(c)) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(Character.toUpperCase(c));
robot.keyRelease(Character.toUpperCase(c));
if (Character.isUpperCase(c)) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
}
robot.delay(delay);
}

Wolfii
- 355
- 3
- 9
-
-
Oh sorry I used an wrapper for the Cahracter class and eclipse must have "thougt" i want to use it there :D I corrected it. – Wolfii Mar 07 '13 at 18:50
-
1The KeyStroke way seems to be invoking `getKeyStroke(int, int)` rather than `getKeyStroke(Character, int)`. – Mar 01 '14 at 00:05
-
There must be more to it, because this method doesn't work for me. My "h" becomes an "8" when I plug the resulting key code into `Robot.keyPress` – Jason Nov 01 '17 at 19:40
3
A lot more verbose but more customizable
import java.awt.AWTException;
import java.awt.Robot;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;
public class AsciiKeyTyper {
private Map<Character,KeyStroke> strokeMap;
private Robot robot;
public AsciiKeyTyper() throws AWTException{
robot=new Robot();
//initialize a map from the input char to the keystroke,
//using the fact that sometimes the KeyEvent key codes correspond to ASCII
strokeMap=new HashMap<Character,KeyStroke>(){
private static final long serialVersionUID = 1L;{
put('\n',new KeyStroke(KeyEvent.VK_ENTER,false));
put('\t',new KeyStroke(KeyEvent.VK_TAB,false));
put('\r',new KeyStroke(KeyEvent.VK_HOME,false));
put(' ',new KeyStroke(KeyEvent.VK_SPACE,false));
put('!',new KeyStroke(KeyEvent.VK_1,true));
put('"',new KeyStroke(KeyEvent.VK_QUOTE,true));
put('#',new KeyStroke(KeyEvent.VK_3,true));
put('$',new KeyStroke(KeyEvent.VK_4,true));
put('%',new KeyStroke(KeyEvent.VK_5,true));
put('&',new KeyStroke(KeyEvent.VK_7,true));
put('\'',new KeyStroke(KeyEvent.VK_QUOTE,false));
put('(',new KeyStroke(KeyEvent.VK_9,true));
put(')',new KeyStroke(KeyEvent.VK_0,true));
put('*',new KeyStroke(KeyEvent.VK_8,true));
put('+',new KeyStroke(KeyEvent.VK_EQUALS,true));
put(',',new KeyStroke(KeyEvent.VK_COMMA,false));
put('-',new KeyStroke(KeyEvent.VK_MINUS,false));
put('.',new KeyStroke(KeyEvent.VK_PERIOD,false));
put('/',new KeyStroke(KeyEvent.VK_SLASH,false));
for(int i=(int)'0';i<=(int)'9';i++){
put((char)i,new KeyStroke(i,false));
}
put(':',new KeyStroke(KeyEvent.VK_SEMICOLON,true));
put(';',new KeyStroke(KeyEvent.VK_SEMICOLON,false));
put('<',new KeyStroke(KeyEvent.VK_COMMA,true));
put('=',new KeyStroke(KeyEvent.VK_EQUALS,false));
put('>',new KeyStroke(KeyEvent.VK_PERIOD,true));
put('?',new KeyStroke(KeyEvent.VK_SLASH,true));
put('@',new KeyStroke(KeyEvent.VK_2,true));
for(int i=(int)'A';i<=(int)'Z';i++){
put((char)i,new KeyStroke(i,true));
}
put('[',new KeyStroke(KeyEvent.VK_OPEN_BRACKET,false));
put('\\',new KeyStroke(KeyEvent.VK_BACK_SLASH,false));
put(']',new KeyStroke(KeyEvent.VK_CLOSE_BRACKET,false));
put('^',new KeyStroke(KeyEvent.VK_6,true));
put('_',new KeyStroke(KeyEvent.VK_MINUS,true));
put('`',new KeyStroke(KeyEvent.VK_BACK_QUOTE,false));
for(int i=(int)'A';i<=(int)'Z';i++){
put((char)(i+((int)'a'-(int)'A')),new KeyStroke(i,false));
}
put('{',new KeyStroke(KeyEvent.VK_OPEN_BRACKET,true));
put('|',new KeyStroke(KeyEvent.VK_BACK_SLASH,true));
put('}',new KeyStroke(KeyEvent.VK_CLOSE_BRACKET,true));
put('~',new KeyStroke(KeyEvent.VK_BACK_QUOTE,true));
}};
}
public void typeKey(char key){
try{
strokeMap.get(key).type();
}catch(NullPointerException ex){
System.err.println("'"+key+"': no such key in mappings");
}
}
private class KeyStroke{
int code;
boolean isShifted;
public KeyStroke(int keyCode,boolean shift){
code=keyCode;
isShifted=shift;
}
public void type(){
try{
if (isShifted) {
robot.keyPress(KeyEvent.VK_SHIFT);
}
robot.keyPress(code);
robot.keyRelease(code);
if (isShifted) {
robot.keyRelease(KeyEvent.VK_SHIFT);
}
if(code==KeyEvent.VK_ENTER){
robot.keyPress(KeyEvent.VK_HOME);
robot.keyRelease(KeyEvent.VK_HOME);
}
}catch(IllegalArgumentException ex){
String ch="";
for(char key:strokeMap.keySet()){
if(strokeMap.get(key)==this){
ch=""+key;
break;
}
}
System.err.println("Key Code Not Recognized: '"+ch+"'->"+code);
}
}
}
}

Austin_Anderson
- 900
- 6
- 16
-1
Use reflection!
KeyEvent.class.getField("VK_"+keyName);

Bruce
- 8,609
- 8
- 54
- 83

Alex Suhinin
- 66
- 3
-
-
1while it is (possibly) the shortest and most clever solution, it generally not that recommended to use reflection for a case like this. – NotAFlyingGoose Sep 14 '20 at 14:45