简体   繁体   中英

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!

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 
...

Match your input against ^[0-9A-Za-z]$ or ^[\\\\w&&[^_]]$

if(!key.matches("[0-9A-Za-z]")) 
  throw new IllegalArgumentException("invalid input ...");

and

int code = key.charAt(0);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM