JPanel不对KeyBindings做出反应 [英] JPanel doesn't react to KeyBindings

查看:68
本文介绍了JPanel不对KeyBindings做出反应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个需要JPanel对按下的逃逸键作出反应的应用程序. 我很确定我使用了正确的方法来将键绑定注册到组件,但是显然我仍然做错了什么.这是负责注册对所述键绑定做出反应的代码:

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

初始化所有其他组件后,将在JPanel的构造函数中调用此方法.我尝试调试它,发现该动作本身已在JPanel中注册,但是从未达到actionPerformed()方法中的代码.我怀疑这个JPanel可能没有焦点,因为我在上面的JFrame中使用CardLayout.我衷心希望有人能帮助我,因为它阻碍了我的进步.

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.

推荐答案

您错过了

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

这篇关于JPanel不对KeyBindings做出反应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆