Java:更改“VK_UP”到KeyEvent.VK_UP [英] Java: change "VK_UP" to KeyEvent.VK_UP
问题描述
我需要将>VK_UP
(或简单地UP
)等文本更改/解析为< Java中的code> KeyEvent.VK_UP 常量。我不想使用数字 38
,因为它会保存在 .txt
配置文件中,所以任何人都可以重写它最好的解决办法是有这个散列图:
HashMap< String,Integer> keyConstant;
其中key是名称(VK_UP$ c $ (code> 38
)。
现在的问题是:我怎样才能得到这张地图不需要花费一整晚的时间来手工创建它?
您可以使用反射。
以下各行中的内容应该起作用,例外处理:
public static int parseKeycode(String keycode ){
//假设keycode的格式为VK_ {KEY}
Class keys = KeyEvent.class; //这是存储所有密钥的地方。
Field key = keys.getDeclaredField(keycode); //按名称获取字段。
int keycode = key.get(null); // VK_ {KEY}字段是静态的,所以我们传递'null'作为反射访问器的实例。
返回键码;
}
或者,您可以使用简单的单行程式:
KeyEvent.class.getDeclaredField(keycode).get(null);
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?
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);
这篇关于Java:更改“VK_UP”到KeyEvent.VK_UP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!