How to add JMenuBar shortcuts?

Adding shortcuts to JMenuBar submenu items in the Java Swing GUI design is obvious, but how do I add shortcuts to JMenuBar main menu items?

+7
java swing jmenubar
source share
2 answers

You have two types of keyboard shortcuts: mnemonics and accelerators.

Mnemonics are usually triggered using Alt + KEY. This is a letter that is underlined in the text of a menu item (for example, F for a file). Accelerators are application shortcuts that are usually launched using Ctrl + KEY.


To use mnemonics, you can use the setMnemonic() method:

 menuItem.setMnemonic('F'); 

To use accelerators, you must use the setAccelerator() method.

 menuItem.setAccelerator(KeyStroke.getKeyStroke( java.awt.event.KeyEvent.VK_S, java.awt.Event.CTRL_MASK)); 
+19
source share

The Sun / Oracle website has a great tutorial on using JMenu. When you use the shortcut keys, Java uses mnemonics or an accelerator depending on the shortcut you want to use. you can set mnemonics using the following

 menuItem.setMnemonic(KeyEvent.VK_T); 

and accelerator through

  menuItem.setAccelerator(KeyStroke.getKeyStroke( KeyEvent.VK_T, ActionEvent.ALT_MASK)); 

These are both examples taken from the link above.

+2
source share

All Articles