有没有办法从java.awt.event.KeyEvent
映射中获取所有键?
我尝试使用反射,例如:
for (Field f : KeyEvent.class.getDeclaredFields()) {
try
{
map.put((int)f.getInt(f), f.getName());
}
catch (IllegalArgumentException | IllegalAccessException ex) {
Logger.getLogger(KeyCollection.class.getName()).log(Level.SEVERE, null, ex);
}
}
但我得到了:
java.lang.IllegalAccessException: Class com.util.KeyCollection can not access a member of class java.awt.event.KeyEvent with modifiers "private"
更新:这是我想出的使用 assylias 代码示例:
for (Field f : KeyEvent.class.getDeclaredFields()) {
try {
if (java.lang.reflect.Modifier.isStatic(f.getModifiers()) && f.getType() == int.class && f.getName().startsWith("VK")) {
f.setAccessible(true);
map.put((int)f.get(null), f.getName());
}
} catch (IllegalArgumentException | IllegalAccessException ex) {
ex.printStackTrace();
}
}