Reputation: 43
I have four radio buttons and they're all part of a radioGroup. How can I link hotkeys to each of the buttons? What I want to do is link the keys '1', '2', '3' and '4' to each corresponding radiobutton.
buttonGroup1 = new javax.swing.ButtonGroup();
quizBut1 = new javax.swing.JRadioButton();
quizBut2 = new javax.swing.JRadioButton();
quizBut4 = new javax.swing.JRadioButton();
quizBut3 = new javax.swing.JRadioButton();
Upvotes: 1
Views: 2272
Reputation: 436
as well, you could use ActionMap and KeyStroke. Some rough snippet, modify it:
class KeyAction extends AbstractAction {
JRadioButton b;
KeyAction(JRadioButton b) {
super();
this.b = b;
}
@Override
public void actionPerformed(ActionEvent e) {
b.setSelected(true);
}
}
b1.setAction(new KeyAction(b1));
b2.setAction(new KeyAction(b2));
b3.setAction(new KeyAction(b3));
bindHotkey('1', "1", b1.getAction());
bindHotkey('2', "2", b2.getAction());
bindHotkey('3', "3", b3.getAction());
..............
void bindHotkey(char keyChar, String name, Action action) {
KeyStroke ks = KeyStroke.getKeyStroke(keyChar);
container.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(ks, name);
container.getActionMap().put(name, action);
}
Upvotes: 3
Reputation: 33954
Use a KeyListener - you can attach them to just about any component in Swing.
What you'll probably do is attach a KeyListener to the primary JFrame in your application to capture all keypresses, and depending on which key was pressed, you will then trigger changes in the UI accordingly (e.g the selecting of a given radio button).
It's important that you attach the KeyListener to a container that will have keybaord focus pretty much all the time. You cannot, in this case, attach the KeyListener to the radio buttons themselves because the KeyListeners only see events for which they have focus. When a KeyEvent isn't absorbed by a given object, the KeyEvent is then passed on to its parent component to see if it wants to do anything with the event, and on and on all the way up to the application's window. If no KeyListener does anything with the event and you've gone all the way to the root of the component hierarchy, then nothing happens in response to the keypress and the event is essentially discarded.
Upvotes: 4