gpt4 book ai didi

Java:将 "VK_UP"更改为 KeyEvent.VK_UP

转载 作者:行者123 更新时间:2023-11-29 05:41:35 28 4
gpt4 key购买 nike

我需要将 "VK_UP"(或简单的 "UP")之类的文本更改/解析为 Java 中的 KeyEvent.VK_UP 常量.我不想使用数字 38,因为它将保存在 .txt 配置文件中,因此任何人都可以重写它。

最好的解决方案是拥有这个 HashMap :

HashMap<String, Integer> keyConstant;

其中键是名称 ("VK_UP"),值是键码 (38)。

现在的问题是:我怎样才能得到这张 map 而不用花一整晚的时间手动创建它?

最佳答案

你可以使用反射。

下面几行应该可以工作,没有异常处理:

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

关于Java:将 "VK_UP"更改为 KeyEvent.VK_UP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17372011/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com