kajacx
kajacx

Reputation: 12939

Java: change "VK_UP" to KeyEvent.VK_UP

I need to change/parse text like "VK_UP" (or simply "UP") to the KeyEvent.VK_UP constant in Java. I dont want to use the number 38 instead since it will be saved in a .txt config file so anybody could rewrite it.

Best solution would be to have this hashmap:

HashMap<String, Integer> keyConstant;

Where key would be the name ("VK_UP") and value would be key code (38).

Now the question is: How can I get this map without spending all evening creating it manually?

Upvotes: 1

Views: 643

Answers (1)

Xyene
Xyene

Reputation: 2364

You can use reflection.

Something among the lines of the following should work, sans exception handling:

public static int parseKeycode(String keycode) {
    // We assume keycode is in the format VK_{KEY}
    Class keys = KeyEvent.class; // This is where all the keys are stored.
    Field key = keys.getDeclaredField(keycode); // Get the field by name.
    int keycode = key.get(null); // The VK_{KEY} fields are static, so we pass 'null' as the reflection accessor's instance.
    return keycode;
}

Alternatively, you could use a simple one-liner:

KeyEvent.class.getDeclaredField(keycode).get(null);

Upvotes: 3

Related Questions