Java: change “VK_UP” to KeyEvent.VK_UP

断了今生、忘了曾经 提交于 2019-12-23 02:44:35

问题


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?


回答1:


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);


来源:https://stackoverflow.com/questions/17372011/java-change-vk-up-to-keyevent-vk-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!