How To: Set Shortcut Keys For JFrame Menus

Here's how to add shortcut keys for a JMenuItem object named quit. Remember to have an ActionListener for the menu item in order for the shortcut key to have something to shortcut to!

    // create a menu item
    JMenuItem quit = new JMenuItem("Quit");
    ...

    // allow pressing Q to select quit from the visible menu
    quit.setMnemonic(KeyEvent.VK_Q);

    // allow Ctrl-Q to select quit when menu is not visible
    quit.setAccelerator(
      KeyStroke.getKeyStroke(
        KeyEvent.VK_Q,
        Event.CTRL_MASK));

    // ...and do not forget the listener
    quit.addActionListener(new ActionListener()
    {
      public void actionPerformed(ActionEvent e)
      {
        System.exit(0);
      }
    });