I have JButton performing some action via ActionListener. After I try to use Action to bind a keyboard shortcut (following this), mouse click on button works, but no reaction to keyboard.
Code Before
Button created within a panel, actionListener added.
private FooActionListener actionListener = new FooActionListener();
buttonLeft = new JButton("Left");
up.addActionListener(actionListener);
Then, actionPerformed method within FooActionListener class outside the main class:
public void actionPerformed(ActionEvent e) {
Object source = e.getSource();
if (source == buttonLeft) { thing.move(Direction.LEFT); }
}
Code After
final String leftText = "Left";
final Action left = new AbstractAction() {
@Override
public void actionPerformed(ActionEvent e) {
thing.move(Direction.LEFT);
}
};
buttonLeft = new JButton(left);
buttonLeft.setText(leftText);
KeyStroke keyLeft = KeyStroke.getKeyStroke(KeyEvent.VK_A, 0);
buttonLeft.getInputMap(buttonLeft.WHEN_IN_FOCUSED_WINDOW).put(keyLeft,
"Left");
buttonLeft.getActionMap().put("Left", left );
Update: I am not quite sure that new code actually performs with the mouse as it should. Let’s say the object supposed to move 25 pixels by one click, and it does in the original code. But with the new action it seems that it moves twice or even trice with each click, which suggests some weird behavior of an action.