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.

myMenuItem.setMnemonic('x');
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));
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact