Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java swing keybinding

This is in the constructor of a JPanel but it does not print anything when I press "h". If more code is needed, I can provide it. Thank you!

String hide = "hide";
    this.getInputMap().put(KeyStroke.getKeyStroke('h'), hide);
    this.getActionMap().put(hide, new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
                System.out.println("HIDDEN");
            if (isHidden){
                slide.setVisible(true);
            }else{
                slide.setVisible(false);
            }
        }
    });
like image 776
Yesha Avatar asked Jun 30 '13 04:06

Yesha


1 Answers

this.getInputMap()....

You are trying to add the bindings to the default InputMap, which is the InputMap when the component has focus. By default a JPanel does not have focus.

You should try using one of the other InputMaps by using the getInputMap(int) method. Or you will need to make the panel focusable and give it focus.

Read the Swing tutorial on How to Use Key Bindings for more information on the proper variables to use to specify the desired InputMap.

like image 118
camickr Avatar answered Sep 28 '22 10:09

camickr