使用keyBindings(作为@trashgod已经提到)是的的方式。为了得到完全相同的视觉行为仿佛空间激活按钮/输入(当它是重点)
- 实施的行动是委托/发布
- 需要结合两种按下按下注册按钮的默认操作和释放的键来模拟
- 安装绑定到按钮的父在其类型的InputMap WHEN_ANCESTOR
在代码:
// 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));
}
是的,我的道歉。通常当我收到一个可用的答案时,我有点太仓促和风暴来利用它。我为此道歉。 – Sven
1)也许考虑[Key Bindings](http://docs.oracle.com/javase/tutorial/uiswing/misc/keybinding.html)。 2)为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 3)请好好打听那个其他事情。 :) –