How to add JMenuBar shortcuts?

jacknad picture jacknad · Sep 15, 2010 · Viewed 20.2k times · Source

Adding shortcuts to JMenuBar submenu items in the Java Swing GUI designer is obvious, but how are shortcuts added to JMenuBar main menu items?

Answer

Vivien Barousse picture Vivien Barousse · Sep 15, 2010

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));