views:

1049

answers:

4

How do you get the VK code from a char that is a letter? It seems like you should be able to do something like javax.swing.KeyStroke.getKeyStroke('c').getKeyCode(), but that doesn't work (the result is zero). Everyone knows how to get the key code if you already have a KeyEvent, but what if you just want to turn chars into VK ints? I'm not interested in getting the FK code for strange characters, only [A-Z],[a-z],[0-9].

Context of this problem -------- All of the Robot tutorials I've seen assume programmers love to spell out words by sending keypresses with VK codes:

int keyInput[] = {
      KeyEvent.VK_D,
      KeyEvent.VK_O,
      KeyEvent.VK_N,
      KeyEvent.VK_E
  };//end keyInput array

Call me lazy, but even with Eclipse this is no way to go about using TDD on GUIs. If anyone happens to know of a Robot-like class that takes strings and then simulates user input for those strings (I'm using FEST), I'd love to know.

A: 

I don't think there is an easy answer for this.

First realize that java has two byte chars and not nearly 2^16 KeyEvent.VK_'s defined. So there are going to be chars for which no KeyEvent can be generated to get that output.

Also, C and c and Ç and ç all have the same KeyEvent.getKeyCode() == KeyEvent.VK_C.

Clint
+3  A: 

Maybe this ugly hack:

Map<String, Integer> keyTextToCode = new HashMap<String, Integer>(256);
Field[] fields = KeyEvent.class.getDeclaredFields();
for (Field field : fields) {
    String name = field.getName();
    if (name.startsWith("VK_")) {
        keyTextToCode.put(name.substring("VK_".length()).toUpperCase(),
                          field.getInt(null));
    }
}

keyTextToCode would then contain the mapping from strings (e.g. "A" or "PAGE_UP") to vk codes.

fulkod
+1 very good, just note that exceptions handling is missing
dfa
A: 
AWTKeyStroke.getAWTKeyStroke("C").getKeyCode();
Pace