Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JPanel doesn't react to KeyBindings

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.

like image 985
Exevan Avatar asked Nov 02 '12 19:11

Exevan


1 Answers

you miss there

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

like image 196
mKorbel Avatar answered Sep 19 '22 06:09

mKorbel