我需要将"VK_UP" (或简称为"UP")之类的文本更改/解析为Java语言中的KeyEvent.VK_UP常量。我不想使用数字38,因为它将被保存在.txt配置文件中,这样任何人都可以重写它。
最好的解决方案是有这样的hashmap:
HashMap<String, Integer> keyConstant;其中,键是名称("VK_UP"),值是键代码(38)。
现在的问题是:我如何才能在不花费整个晚上的时间手动创建地图的情况下获得它?
发布于 2013-06-29 03:25:38
您可以使用反射。
以下几行中的某些内容应该可以工作,即无异常处理:
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;
}或者,您可以使用简单的一行代码:
KeyEvent.class.getDeclaredField(keycode).get(null);https://stackoverflow.com/questions/17372011
复制相似问题