5

我正在用 Java 编写一个程序,使用 Swing,带有一个包含箭头键的 GUI。方向键对应键盘上的方向键。

当我按下键盘上的向上箭头键时,我希望 GUI 上的向上箭头键显示为被按下。在我释放箭头键之前,它应该显示它仍然被按下,并且在释放时它也应该释放。

到目前为止我的代码片段(仅适用于“向上”按钮),我认为这在被按下的节目类别中是完全错误的:

...
if (e.getKeyCode() == KeyEvent.VK_UP) {
                    actionArrowUp();
                    JButton buttonUp = (JButton) mainTab.getComponent(4);
                    buttonUp.setSelected(true);
                }
...
@Override
public void keyReleased(KeyEvent e) { 
            if (e.getKeyCode() == KeyEvent.VK_UP)
                actionArrowUpRelease();
                buttonUp.setSelected(true);
4

2 回答 2

4

LinePanel使用Key Bindings并调用doClick()inactionPerformed()来实现类似于您描述的效果。

附录:由于您希望按钮在按下键显示为按下状态,您可以使用可选onKeyReleased参数KeyStroke.getKeyStroke(). 如 中所述ButtonModel,您需要使模型同时启用并按下以模拟鼠标按下按钮。

于 2012-10-20T12:58:47.710 回答
4

使用 keyBindings (正如@trashgod 已经提到的)是要走的路。获得与通过空格/输入激活按钮完全相同的视觉行为(当它被聚焦时)

  • 实现委托给为按下/释放按钮注册的默认操作的操作
  • 需要绑定到按键的按下和释放来模拟
  • 在 WHEN_ANCESTOR 类型的 inputMap 中安装到按钮父级的绑定

在代码中:

// the delegating  action
public static class SimulateButtonAction extends AbstractAction {

    AbstractButton button;

    public SimulateButtonAction(AbstractButton model, String fire) {
        super(fire);
        this.button = model;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        Action delegate = button.getActionMap().get(getName());
        delegate.actionPerformed(new ActionEvent(button, 
                ActionEvent.ACTION_PERFORMED, getName()));
    }

    public String getName() {
        return (String) getValue(Action.NAME);
    }

}

// example usage
JComponent content = new JPanel(new GridLayout(0, 5));
Action log = new AbstractAction() {

    @Override
    public void actionPerformed(ActionEvent e) {
        System.out.println("triggered: " + ((AbstractButton) e.getSource()).getText());
    }

};
String pressed = "pressed";
String released = "released";
ActionMap actionMap = content.getActionMap();
InputMap inputMap = content.getInputMap(JComponent.WHEN_ANCESTOR_OF_FOCUSED_COMPONENT);
String[] arrows = {"UP", "DOWN", "LEFT", "RIGHT"};
for (int i = 0; i < arrows.length; i++) {
    JButton button = new JButton(log);
    button.setAction(log);
    button.setText(arrows[i]);
    content.add(button);
    // simulate pressed
    String pressedKey = pressed + arrows[i];
    inputMap.put(KeyStroke.getKeyStroke(arrows[i]), pressedKey);
    actionMap.put(pressedKey, new SimulateButtonAction(button, pressed));
    String releasedKey = released + arrows[i];
    inputMap.put(KeyStroke.getKeyStroke(released + " " +arrows[i]), releasedKey);
    actionMap.put(releasedKey, new SimulateButtonAction(button, released));
}
于 2012-10-20T14:26:51.733 回答