Java:Keybindings被其他组件占用

时间:2012-10-29 14:55:08

标签: java swing jpanel key-bindings jtabbedpane

我正在开发GUI。

Gui的构造如下:一个JFrame包含一个(自定义)leftPanel和rightPanel。 RightPanel是tabbedpane的扩展,包含一个标签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的其他组件之一或者面板本身已经将该键绑定用于其他内容。

我试图清除类本身的输入映射和动作映射(this.getInputMap()。clear()),但问题仍然存在。任何解决方案?

1 个答案:

答案 0 :(得分:0)

当您注册箭头键击但未执行相应的操作时(与其他键击相关的操作,如字母,工作完全正常),原因可能是JButton或{{1}组件上某处拦截这些箭头键击。

要解决此问题,请致电JTextFieldyourJButton.setFocusable(false)。这将阻止yourJTextfield.setFocusable(false)JButton消耗箭头键。