简体   繁体   中英

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);
            }
        }
    });
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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM