How do I create shortcuts for menu items using Swing components?

Simon Brown

Using Swing, there are two different types of "shortcuts" available to you.

Firstly, you can assign mnemonics to the menus and menu items. To do this, just call the setMnemonic(char) method passing the character you wish to use for the mnemonic. For example, an "Exit" menu item could have a mnemonic of 'x', meaning that when the File menu is open, the user can press the X key to select the menu item.

You can assign mnemonics to menus in the same way.

The other choice you have is assigning an accelerator to a menu item. For example, Ctrl-S is frequently used to save an open document. To do this, call the setAccelerator(KeyStroke) method, as follows :
myMenuItem.setAccelerator(KeyStroke.getKeyStroke(KeyEvent.VK_S, KeyEvent.CTRL_MASK));