Java swing keybinding

2019-06-22 08:16发布

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

1条回答
一夜七次
2楼-- · 2019-06-22 09:06
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.

查看更多
登录 后发表回答