Java Swing Tutorial - Java Swing Menu

The following steps describe the process of how to create add menu to our application.

Create an object of the JMenuBar class and add it to a JFrame using its setJMenuBar() method. Add the JMenu to the JMenuBar. A JMenu is a container that can hold menu items that represent the options.

JMenuBar menuBar = new JMenuBar(); 

The following code creates two JMenu: File and Help, and add them to the JMenuBar.

JMenu fileMenu = new JMenu("File"); 
JMenu helpMenu = new JMenu("Help"); 

The following code creates menu items to the menu.

JMenuItem newMenuItem = new JMenuItem("New"); 
JMenuItem openMenuItem = new JMenuItem("Open"); 
JMenuItem exitMenuItem = new JMenuItem("Exit");

The following code add menu items and a separator to the menu


To add shortcuts to menu options, use the setMnemonic() method and specify a shortcut key.

We can invoke the menu item by pressing a combination of the Alt key and the shortcut key.

The following code sets the E key as a mnemonic and Ctrl + E as an accelerator for the Exit menu option:

// Set E as mnemonic for Exit menu and  Ctrl + E  as  its  accelerator exitMenuItem.setMnemonic(KeyEvent.VK_E);
KeyStroke cntrlEKey = KeyStroke.getKeyStroke(KeyEvent.VK_E, ActionEvent.CTRL_MASK);

Now we can invoke the Exit menu option in two ways.

  • press Alt + E key combination when it is visible.
  • press Ctrl + E keys combination any time.


The creation of a pop-up menu is similar to a JMenu by using the JPopupMenu class.

The following code shows how to create a popup menu.

JPopupMenu popupMenu = new JPopupMenu();

// Create three menu items for our  popup  menu 
JMenuItem popup1  = new JMenuItem("Poupup1"); 
JMenuItem popup2  = new JMenuItem("Poupup2"); 
JMenuItem popup3  = new JMenuItem("Poupup3");

// Add menu items to the   popup  menu 

The following code shows a popup menu when clicking right mouse button. It uses its show() method to display the menu.

The show() method takes three arguments: the invoker component, x and y coordinates on the invoker component.

// Create a  mouse listener
MouseListener ml = new MouseAdapter()  {
    public void  mousePressed(MouseEvent e)  {
        if (e.isPopupTrigger()) {
  , e.getX(), e.getY());
    public void  mouseReleased(MouseEvent e)  {
        if (e.isPopupTrigger()) {
  , e.getX(), e.getY());

// Add a  mouse listener to myComponent