使用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)請好好打聽那個其他事情。 :) –