gpt4 book ai didi

Java Swing : Show pressed button when using corresponding keyboard button

转载 作者:搜寻专家 更新时间:2023-10-31 19:40:21 25 4
gpt4 key购买 nike

我正在使用 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);

最佳答案

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

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

在代码中:

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

关于Java Swing : Show pressed button when using corresponding keyboard button,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12987557/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com