Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add JMenuBar shortcuts?

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

like image 944
jacknad Avatar asked Sep 15 '10 13:09

jacknad


2 Answers

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));
like image 147
Vivien Barousse Avatar answered Sep 22 '22 05:09

Vivien Barousse


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

like image 22
Sean Avatar answered Sep 20 '22 05:09

Sean