Adding shortcuts to JMenuBar submenu items in the Java Swing GUI designer is obvious, but how are shortcuts added to JMenuBar main menu items?
Asked
Active
Viewed 2.1k times
7
-
Are you looking for a way to do it programatically or through the GUI designer? If the GUI designer, what IDE are you using? Is this Netbeans? – Mark Peters Sep 15 '10 at 13:28
-
I would like to know how to do it programatically? – Doug Hauf Feb 12 '14 at 21:25
2 Answers
21
You have two types of keyboard shortcuts: mnemonics and accelerators.
Mnemonics are usually triggered using Alt+KEY. That's the letter that's underlined in the menu item text (F for File, for example). Accelerators are application-wide shortcuts that are usually triggered using Ctrl+KEY.
To use mnemonics, you can use the setMnemonic()
method:
menuItem.setMnemonic('F');
To use accelerators, you have to use the setAccelerator()
method.
menuItem.setAccelerator(KeyStroke.getKeyStroke(
java.awt.event.KeyEvent.VK_S,
java.awt.Event.CTRL_MASK));

Vivien Barousse
- 20,555
- 2
- 63
- 64
-
-
1Note that `setMnemonic` always uses the first occurrence of the letter (see `SwingUtilities#findDisplayedMnemonicIndex`). If you need to use a latter occurrence, use `AbstractButton#setDisplayedMnemonicIndex`, which corresponds to `Action.DISPLAYED_MNEMONIC_INDEX_KEY`. (BTW I recommend you set action properties then call `AbstractButton#setAction` instead of calling those JComponent methods directly.) – Geoffrey Zheng Sep 16 '10 at 16:54
-
-
am having a problem when using this on a `JMenuItem` in a `JPopupMenu` it wont work unless i press on the `JPopupMenu` and the dropdown of options appears and then while its shown it will work how can i go make the shortcut work without the need to press and show scenario – shareef Mar 11 '15 at 13:46
2
The Sun/Oracle site has a great Tutorial on using JMenu's When you are dealing with shortcut keys, Java uses mnemonic or Accelerator depending on the shortcut you want to use. you can set the mnemonic using the following
menuItem.setMnemonic(KeyEvent.VK_T);
and the accelerator via
menuItem.setAccelerator(KeyStroke.getKeyStroke(
KeyEvent.VK_T, ActionEvent.ALT_MASK));
These are both examples taken from the link above

Sean
- 7,597
- 1
- 24
- 26