سؤال

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);
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top