Java swing keybinding

非 Y 不嫁゛ 提交于 2019-12-12 11:01:19

问题


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:


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.



来源:https://stackoverflow.com/questions/17387037/java-swing-keybinding

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!