Search code examples
javaregexkeyeventkeycode

Java: Convert string to KeyEvent virtual key code?


I'm trying to write a method that will take a single character string and (if possible) return the virtual key code it corresponds to.

For instance:

private static int getKeyCode(final String key) {
    if(key.length != 1)
        throw new IllegalArgumentException("Only support single characters");

    // Also check to see if the 'key' is (1-9)(A-Z), otherwise exception

    // How to perform the conversion?
}

// Returns KeyEvent.VK_D
MyKeyUtils.getKeyCode("D");

Thus, passing MyKeyUtils.getKeyCode("blah") throws an IllegalArgumentException because "blah" has 4 chars. Also, passing MyKeyUtils.getKeyCode("@")throws the same exception because "@" is neither a digit 0-9 or a character A - Z.

Any ideas how to do the regex check as well as the actual conversion? Thanks in advance!


Solution

  • if (key.matches("[^1-9A-Z]"))
      throw new IllegalArgumentException("...");
    

    Convertion can be done using (int) key.charAt(0) value, because:

    public static final int VK_0 48 
    public static final int VK_1 49 
    ...
    public static final int VK_9 57 
    public static final int VK_A 65 
    ...