Java Swing Tutorials - Herong's Tutorial Examples - Version 4.10, by Dr. Herong Yang

setAccelerator() - Setting Keyboard Accelerators on Menu Items

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

Keyboard mnemonics allows users to invoke a menu item with a single key. But the menu contains that menu item must be popped up first.

For users to invoke a menu item without its menu popped up, we need to assign an accelerator, key combination, to that menu item with the setAccelerator() method. Here is how it works:

1. Assign difference accelerators, representing different key combinations, to different menu items.

2. Adding an action listener to each menu item.

3. When an accelerator, key combination, is pressed at any time, the menu item with the matching accelerator will fire an action event.

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

/* JMenuItemSetAcceleratorTest.java
 * Copyright (c) 2014, HerongYang.com, All Rights Reserved.
 */
import java.awt.event.*;
import javax.swing.*;
import javax.swing.event.*;
public class JMenuItemSetAcceleratorTest implements ActionListener {
   JFrame myFrame = null;
   public static void main(String[] a) {
      (new JMenuItemSetAcceleratorTest()).test();
   }
   private void test() {
      myFrame = new JFrame("Menu Item Accelerator 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.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_P, ActionEvent.CTRL_MASK));
      myItem.addActionListener(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.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_D, ActionEvent.CTRL_MASK));
      myItem.addActionListener(this);
      myGroup.add(myItem);
      myMenu.add(myItem);

      myItem = new JRadioButtonMenuItem("Green");
      myItem.setMnemonic(KeyEvent.VK_G);
      myItem.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_N, ActionEvent.CTRL_MASK));
      myItem.addActionListener(this);
      myGroup.add(myItem);
      myMenu.add(myItem);

      myItem = new JRadioButtonMenuItem("Blue");
      myItem.setMnemonic(KeyEvent.VK_B);
      myItem.setAccelerator(
         KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK));
      myItem.addActionListener(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());
   }
}

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

Don't open the "Color" menu, and press <Ctrl>-d, <Ctrl>-n and <Ctrl>-e. Then repeat the test with the "Color" menu open. Also try <Ctrl>-p. You will see some messages printed on the Java console window:

Item clicked: Red
Item clicked: Green
Item clicked: Blue
Item clicked: Red
Item clicked: Green
Item clicked: Blue
Item clicked: Help

Interesting notes about this tutorial example:

  • I implemented only one interface on the main class: ActionListener.
  • "myItem.setAccelerator( KeyStroke.getKeyStroke( KeyEvent.VK_*, ActionEvent.CTRL_MASK ) );" statement is used to assign a specific accelerator to a menu item.
  • Most GUI applications follow the convention of using <Ctrl> as the modifier key menu item accelerators.
  • When accelerator <Ctrl>-d was pressed, 1 action event was fired from the "Red" menu item, because it has the matching accelerated assigned.
  • The accelerator on the "Help" menu item listed in the menu bar also works correctly.

Sample programs listed in this section have been tested with JDK 1.6.0 to 1.8.0.

Last update: 2014.

Table of Contents

 About This Java Swing Tutorial Book

 Introduction of Java Swing Package

 Graphics Environment of the Local System

 JFrame - Main Frame Class

 JLabel - Swing Label Class

 JButton - Swing Button Class

 JRadioButton - Swing Radio Button Class

 JTextField - Swing Text Field 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

 MenuItemActionListenerTest.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

 References

 Printable Copy - PDF Version

setAccelerator() - Setting Keyboard Accelerators on Menu Items - Updated in 2014, by Dr. Herong Yang