Is there a way to get all Keys from java.awt.event.KeyEvent
to map?
I tried using reflection like:
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);
}
}
But I got:
java.lang.IllegalAccessException: Class com.util.KeyCollection can not access a member of class java.awt.event.KeyEvent with modifiers "private"
UPDATE: Here is what I came up with using assylias code example:
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();
}
}
Using your approach, you need to make the field accessible first:
f.setAccessible(true);
But there also is an issue with the way you try to get the field. The example below works fine and you can adapt as required:
public static void main(String[] args) {
Map<Object, String> map = new HashMap<>();
for (Field f : KeyEvent.class.getDeclaredFields()) {
try {
if (java.lang.reflect.Modifier.isStatic(f.getModifiers())) {
f.setAccessible(true);
map.put(f.get(null), f.getName());
}
} catch (IllegalArgumentException | IllegalAccessException ex) {
ex.printStackTrace();
}
}
System.out.println(map);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.