Java:键绑定(bind)被其他组件消耗

标签 java swing jpanel key-bindings jtabbedpane

我正在开发 GUI。

Gui 的构造如下:包含(自定义)leftPanel 和 rightPanel 的 JFrame。 RightPanel 是选项卡 Pane 的扩展,包含 MainTab 类作为选项卡之一。

Maintab 有以下代码:

private void createKeyBindings(){
    actionMap = this.getActionMap();
    inputMap = this.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW);
    inputMap.put(KeyStroke.getKeyStroke("UP),
            "pressedUpArrow");
    inputMap.put(KeyStroke.getKeyStroke("released UP"),
           "releasedUpArrow");
    actionMap.put("pressedUpArrow",
             new PressedUpArrowAction());
    actionMap.put("releasedUpArrow",
            new ReleasedUpArrowAction());
    inputMap.put(KeyStroke.getKeyStroke("RIGHT"),
            "pressedRightArrow");
    inputMap.put(KeyStroke.getKeyStroke("released RIGHT"),
           "releasedRightArrow");
    actionMap.put("pressedRightArrow",
             new PressedRightArrowAction());
    actionMap.put("releasedRightArrow",
            new ReleasedRightArrowAction());
    inputMap.put(KeyStroke.getKeyStroke("LEFT"),
            "pressedLeftArrow");
    inputMap.put(KeyStroke.getKeyStroke("released LEFT"),
           "releasedLeftArrow");
    actionMap.put("pressedLeftArrow",
             new PressedLeftArrowAction());
    actionMap.put("releasedLeftArrow",
            new ReleasedLeftArrowAction());
    inputMap.put(KeyStroke.getKeyStroke("RIGHT"),
            "pressedRightArrow");
    inputMap.put(KeyStroke.getKeyStroke("released RIGHT"),
           "releasedRightArrow");
    actionMap.put("pressedRightArrow",
             new PressedRightArrowAction());
    actionMap.put("releasedRightArrow",
            new ReleasedRightArrowAction());
    inputMap.put(KeyStroke.getKeyStroke("DOWN"),
            "pressedDownArrow");
    inputMap.put(KeyStroke.getKeyStroke("released DOWN"),
           "releasedDownArrow");
    actionMap.put("pressedDownArrow",
             new PressedDownArrowAction());
    actionMap.put("releasedDownArrow",
            new ReleasedDownArrowAction());
}

因此,当我按下其中一个箭头键以及释放它时,它必须执行一项操作。

但只有当我释放其中一个箭头键时它才会执行某些操作。原因可能是 LeftPanel 或 RightPanel 的其他组件之一或面板本身已经将该键绑定(bind)用于其他用途。

我尝试只清除类本身中的输入映射和 Action 映射( this.getInputMap().clear() ),但问题仍然存在。有什么解决办法吗?

最佳答案

当您注册箭头键击键但相应的操作未执行(而与其他击键相关的操作(如字母)工作得很好)时,原因可能是 JButtonJTextField 组件上的某处正在拦截这些箭头键击。

要解决此问题,请调用 yourJButton.setFocusable(false)yourJTextfield.setFocusable(false)。这将阻止 JButtonJTextField 消耗箭头键击键。

关于Java:键绑定(bind)被其他组件消耗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13124071/

相关文章:

java - Swing - 不规则形状的边框

java - 尝试使用 DefaultTableModel 动态地将数据添加到 JTable 但它不起作用

java - 在 borderlayout 中使用 JPanel 错误打包 JFrame

java - 在 Gson 中,如何反序列化任意类的列表映射?

java - Netty websocket SSL 连接 HANDSHAKE_ISSUED

java - JList 星号打印中出现问题

java - Windows 资源管理器类似 Swing 布局

java - 运行时无法将 JButton 添加到 JPanel

java - 如何使用 onFling() 制作 android 脚蹼动画?

Java Hibernate java.lang.IllegalArgumentException : Parameter value did not match expected type