我一直在尝试将箭头键用作我的应用程序的一部分。遵循最佳实践,我坚持使用键绑定。我认为箭头键不会产生键类型事件,所以我采用了这个答案。
但是,我的应用程序有许多组件,我发现如果我的 JFrame 中有一个 JToolbar,则上一个链接中的方法不再有效。为什么会这样,我如何拥有 JToolbar 并使用键绑定?
这是一个SSCCE
public class ArrowTest extends JFrame {
public static void main(final String[] args){
final ArrowTest at = new ArrowTest();
at.setSize(100,200);
final JPanel jp = new JPanel();
jp.setBackground(Color.BLUE);
at.getContentPane().add(jp);
final JToolBar toolbar = new JToolBar();
toolbar.add(new JButton());
//at.add(toolbar);
at.setVisible(true);
}
public ArrowTest() {
super();
this.getContentPane().setLayout(new GridBagLayout());
this.getContentPane().setBackground(Color.BLACK);
this.setKeyBindings();
}
public void setKeyBindings() {
final int condition = JComponent.WHEN_IN_FOCUSED_WINDOW;
final ActionMap actionMap = this.getRootPane().getActionMap();
final InputMap inputMap = this.getRootPane().getInputMap(condition);
for (final Direction direction : Direction.values()) {
inputMap.put(KeyStroke.getKeyStroke(KeyEvent.VK_V,0), direction.getText());
inputMap.put(direction.getKeyStroke(), direction.getText());
actionMap.put(direction.getText(), new MyArrowBinding(direction.getText()));
}
}
enum Direction {
UP("Up", KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0)),
DOWN("Down", KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0)),
LEFT("Left", KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0)),
RIGHT("Right", KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
Direction(final String text, final KeyStroke keyStroke) {
this.text = text;
this.keyStroke = keyStroke;
}
private String text;
private KeyStroke keyStroke;
public String getText() {
return text;
}
public KeyStroke getKeyStroke() {
return keyStroke;
}
@Override
public String toString() {
return text;
}
}
private class MyArrowBinding extends AbstractAction {
private static final long serialVersionUID = -6904517741228319299L;
public MyArrowBinding(final String text) {
super(text);
putValue(ACTION_COMMAND_KEY, text);
}
@Override
public void actionPerformed(final ActionEvent e) {
final String actionCommand = e.getActionCommand();
System.out.println("Key Binding: " + actionCommand);
}
}
}