In the JMenuItem
class you can add a shortkey. Is this possible to add this shortkey to a component or the application without using a JMenu
.

- 2,166
- 4
- 30
- 50

- 67,591
- 47
- 198
- 287
4 Answers
Not only buttons may have mnemonics. Mnemonics (shortcuts) for other components may be specified indirectly through their labels.
You need to create a label for the component and setDisplayedMnemonic for it. Then you attach the label to a component using setLabelFor. The code looks like this:
JLabel lab1 = new JLabel("Text 1");
lab1.setDisplayedMnemonic('e');
JTextField tf1 = new JTextField(20);
lab1.setLabelFor(tf1);

- 7,456
- 3
- 46
- 66
Components that extend AbstractButton
have methods that allow you to set the mnemonic or accelerator. For other you need to do this yourself.
All Swing components use Key Bindings (even the JMenu
you describe above). It works by binding a KeyStroke
to an Action
. To find all the current Swing bindings you can check out Key Bindings. The entry also include a link to the Swing tutorial on "How to Use Key Bindings".
You could attach a KeyListener to any component.
You could process they keystrokes there and process the action desired:
See the tutorial for a complete example:

- 196,001
- 113
- 385
- 569
-
1You could but thats not the way Swing was designed to be used. Swing introduced InputMaps and ActionMaps for this purpose. – camickr Oct 02 '09 at 19:49
-
@camickr: At least that's an option :) Thanks for the comment ;) – OscarRyz Oct 02 '09 at 21:02