How to get the key from the ActionMap

54 views Asked by At

I was wondering how I could get the key code from an AbstractAction in the action map.

for (int key = 37; key <= 122; key++) {
    this.key = key;

    if(!KeyEvent.getKeyText(key).contains("Unknown keyCode")) {
                
        if(KeyInputManager.getInputManager().getOrDefault(key, null) == null)
            KeyInputManager.getInputManager().put(key, true);
                
        component.getActionMap().put(KeyEvent.getKeyText(key), new AbstractAction() {
            @Override
            public void actionPerformed(ActionEvent e) {
                    int keyCode = // TODO: GET KEY CODE HERE
                    KeyInputManager.getInputManager().replace(keyCode, true);
            }
        });
        component.getInputMap().put(KeyStroke.getKeyStroke(key, 0, false), KeyEvent.getKeyText(key));
    }
}

I am trying to store all the key's state (pressed or not) in a HashMap inside KeyInputManager which is accessed through getInputManager. To check if a key is pressed, we can use KeyInputManager.getKeyDown(keyCode) Here is the code for KeyInputManager

public class KeyInputManager {
    private static final HashMap<Integer, Boolean> keysDown = new HashMap<Integer, Boolean>();
    
    public static final boolean keyDown(int keyCode) {
        return keysDown.getOrDefault(keyCode, false);
    }
    
    public static HashMap<Integer, Boolean> getInputManager() {
        return keysDown;
    }
}
1

There are 1 answers

2
Acalinei Beni On

Try this:

int keyCode = (int) e.getActionCommand().charAt(0);

ActionEvent's action command basically contains the key, and since you are using single character keys, taking the first character should give you the key code as an integer.