setMnemonic() - Setting Keyboard Mnemonics on Menu Items

This section provides a tutorial example on how to use setMnemonic() method to associate mnemonics to menu items. Mnemonics allows user to interact with menu items using keys on keyboard.

As you can see from the previous section, it is very hard to use menu key listeners to catch menu key event to support user typed keys on menu items. When one key typed triggers all active menu items to fire menu key events.

Another way to allow users interacting with menu items using keyboard keys is to set mnemonics, keyboard keys, to menu items with the setMnemonic() method. Here is how it works:

1. Assign difference mnemonics, representing different keys on the keyboard, to different menu items.

2. Adding an action listener to each menu item.

3. When a menu item is displayed, the character in the menu text that matches the mnemonic will be underscored.

4. When a key is pressed on the keyboard, only the menu item that has the mnemonic matching the pressed key will fire an action event.

Here is an example program I wrote to test the setMnemonic() method:

/* JMenuItemSetMnemonicTest.java
 * Copyright (c) 1997-2024 HerongYang.com. All Rights Reserved.
 */
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JMenuItemSetMnemonicTest 
   implements ActionListener, MenuKeyListener {
   JFrame myFrame = null;
   public static void main(String[] a) {
      (new JMenuItemSetMnemonicTest()).test();
   }
   private void test() {
      myFrame = new JFrame("Menu Item Mnemonic Test");
      myFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      myFrame.setBounds(50,50,250,150);
      myFrame.setContentPane(new JDesktopPane());

      JMenuBar myMenuBar = new JMenuBar();
      JMenu myMenu = getFileMenu();
      myMenuBar.add(myMenu);
      myMenu = getColorMenu();
      myMenuBar.add(myMenu);
      myMenu = getOptionMenu();
      myMenuBar.add(myMenu);

      JMenuItem myItem = new JMenuItem("Help");
      myItem.setMnemonic(KeyEvent.VK_H);
      myItem.addActionListener(this);
      myItem.addMenuKeyListener(this);
      myMenuBar.add(myItem);

      myFrame.setJMenuBar(myMenuBar);
      myFrame.setVisible(true);
   }
   private JMenu getFileMenu() {
      JMenu myMenu = new JMenu("File");
      JMenuItem myItem = new JMenuItem("Open");
      myMenu.add(myItem);
      myItem = new JMenuItem("Close");
      myMenu.add(myItem);
      myMenu.addSeparator();
      myItem = new JMenuItem("Exit");
      myMenu.add(myItem);
      return myMenu;
   }
   private JMenu getColorMenu() {
      JMenu myMenu = new JMenu("Color");
      ButtonGroup myGroup = new ButtonGroup();

      JRadioButtonMenuItem myItem = new JRadioButtonMenuItem("Red");
      myItem.setSelected(true);
      myItem.setMnemonic(KeyEvent.VK_R);
      myItem.addActionListener(this);
      myItem.addMenuKeyListener(this);
      myGroup.add(myItem);
      myMenu.add(myItem);

      myItem = new JRadioButtonMenuItem("Green");
      myItem.setMnemonic(KeyEvent.VK_G);
      myItem.addActionListener(this);
      myItem.addMenuKeyListener(this);
      myGroup.add(myItem);
      myMenu.add(myItem);

      myItem = new JRadioButtonMenuItem("Blue");
      myItem.setMnemonic(KeyEvent.VK_B);
      myItem.addActionListener(this);
      myItem.addMenuKeyListener(this);
      myGroup.add(myItem);
      myMenu.add(myItem);

      return myMenu;
   }
   private JMenu getOptionMenu() {
      JMenu myMenu = new JMenu("Option");
      JMenuItem myItem = new JMenuItem("Sound");
      myMenu.add(myItem);
      myItem = new JMenuItem("Auto save");
      myMenu.add(myItem);
      return myMenu;
   }
   public void actionPerformed(ActionEvent e) {
      System.out.println("Item clicked: "+e.getActionCommand());
   }
   public void menuKeyTyped(MenuKeyEvent e) {
      MenuElement[] path = e.getPath();
      JMenuItem item = (JMenuItem) path[path.length-1];
      System.out.println("Key typed: "+e.getKeyChar()
         + ", "+e.getKeyText(e.getKeyCode())
         + " on "+item.getText());
   }
   public void menuKeyPressed(MenuKeyEvent e) {
      MenuElement[] path = e.getPath();
      JMenuItem item = (JMenuItem) path[path.length-1];
      System.out.println("Key pressed: "+e.getKeyChar()
         + ", "+e.getKeyText(e.getKeyCode())
         + " on "+item.getText());
   }
   public void menuKeyReleased(MenuKeyEvent e) {
      MenuElement[] path = e.getPath();
      JMenuItem item = (JMenuItem) path[path.length-1];
      System.out.println("Key released: "+e.getKeyChar()
         + ", "+e.getKeyText(e.getKeyCode())
         + " on "+item.getText());
   }
}

If you run this example, you will see the frame window shows up with the menu bar like this:

Menu Item setMnemonic Test (on macOS)
Menu Item setMnemonic Test (on macOS)

If you click the "Color" menu leaving it open, then type the "b" key. Click the "Color" menu and type the "s" key again. You will see some messages printed on the Java console window:

Key pressed: b, B on Red
Key pressed: b, B on Green
Key pressed: b, B on Blue
Item clicked: Blue
Key pressed: s, S on Red
Key pressed: s, S on Green
Key pressed: s, S on Blue
Key pressed: s, S on Help
Key typed: s, Unknown keyCode: 0x0 on Red
Key typed: s, Unknown keyCode: 0x0 on Green
Key typed: s, Unknown keyCode: 0x0 on Blue
Key typed: s, Unknown keyCode: 0x0 on Help
Key released: s, S on Red
Key released: s, S on Green
Key released: s, S on Blue
Key released: s, S on Help

Interesting notes about this tutorial example:

There seems to be a problem with the setMnemonic() method on macOS computers. It is not adding the underscore sign to the mapped key in the menu item. If you run the same program on a Windows computer, you will see underscore signed displayed as shown below.

Menu Item setMnemonic Test (on Windows)
Menu Item setMnemonic Test (on Windows)

Table of Contents

 About This Book

 JDK (Java Development Kit)

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JCheckBox - Swing Check Box Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field Class

 JComboBox - Swing Combo Box Class

Menu Bar, Menus, Menu Items and Listeners

 JMenuBar, JMenu, and JMenuItem Classes

 JMenuBarTest.java - Menu Bar Test Program

 JMenuTest.java - Menu Test Program

 JMenuItemTest.java - Menu Item Test Program

 JRadioButtonMenuItemTest.java - Radio Button Menu Item Test Program

 JCheckBoxMenuItemTest.java - Check Box Menu Item Test Program

 javax.swing.event.MenuListener - Menu Listener Interface

 JMenuItemActionListenerTest.java - Menu Item Action Listener Test

 Item Listener on Radio Button Menu Items

 Item Listener on Check Box Menu Items

 javax.swing.event.MenuKeyListener - Menu Key Listener Interface

setMnemonic() - Setting Keyboard Mnemonics on Menu Items

 setAccelerator() - Setting Keyboard Accelerators on Menu Items

 setMnemonic() - Setting Keyboard Mnemonics on Menus

 Creating Internal Frames inside the Main Frame

 Layout of Components in a Container

 LookAndFeel and UIManager

 Option Dialog Boxes

 JEditorPane - The Editor Pane Class

 SwingWorker - The Background Task Worker

 AWT (Abstract Windows Toolkit)

 Integration with Desktop System

 Archived Tutorials

 References

 Full Version in PDF/EPUB