Java: change “VK_UP” to KeyEvent.VK_UP

本小妞迷上赌 提交于 2019-12-07 02:32:28

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