Reputation: 257
I'm creating a simple Calculator program using Java, Swing.
The keybindings work fine. Well... almost. I ran the software, pressed the number buttons and everything went well, as it should've. Then, I pressed some buttons using my mouse and still, everything is just fine up to this point.
The problem comes when, after pressing the buttons with my mouse the keybindings stop working.
Here's the code for pressing the number 0 (the code for the rest of the buttons are implemented in the same way).
actions[0] = new press0Action();
frame.getRootPane().getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, 0), "0");
frame.getRootPane().getRootPane().getActionMap().put("0", actions[0]);
private class press0Action extends AbstractAction {
@Override
public void actionPerformed(ActionEvent e) {
buttons[0].doClick();
}
}
private void buttonPressed0() {
buttons[0].addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
//Code goes here for pressin the button...
});
}
Thank you for answering in advance! Feel free to add any suggestions for improvement.
P.S.: I've got a feeling it's something to do with the fact that I bound the keys to frame.getRootPane()
Upvotes: 1
Views: 458
Reputation: 20059
You registered your inputs for the root pane, and with no explicit condition. Instead try registering them for the entire window:
actions[0] = new press0Action();
frame.getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_NUMPAD0, 0), "0");
frame.getRootPane().getRootPane().getActionMap().put("0", actions[0]);
Note the alternate getInputMap with argument.
Upvotes: 3