JPanel doesn't react to KeyBindings
Asked Answered
H

1

7

I am working on an application that requires a JPanel to react to the escape key being pressed. I am pretty sure i used the right method for registering keybindings to a component but clearly i am still doing something wrong. This is the code responsible for registering end reacting to the said keybinding:

private void initializeKeyBindings() { 
    Action a = new AbstractAction() {
        private static final long serialVersionUID = 1L;
        @Override public void actionPerformed(ActionEvent e) {
            menu.setVisible(true);
            System.out.println("Herp");
        }
    };
    this.getInputMap().put(KeyStroke.getKeyStroke("ESCAPE"), "ESCAPE");
    this.getActionMap().put("ESCAPE", a);
}

This method is called in the constructor of my JPanel after all other components are initialized. I've tried debugging it and i found that the action itself is registered in the JPanel but the code in the actionPerformed() method is never reached. I suspect there might be a problem with this JPanel not having focus since i am using a CardLayout in the overlying JFrame. I sincerely hope anyone can help me with this as it is holding up my progress very badly.

Helvetii answered 2/11, 2012 at 19:22 Comment(0)
A
10

you miss there

xxx.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(...)

Aegean answered 2/11, 2012 at 20:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.