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(); 
myFrame.setJMenuBar(menuBar);

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"); 
menuBar.add(fileMenu); 
menuBar.add(helpMenu);

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

fileMenu.add(newMenuItem); 
fileMenu.add(openMenuItem); 
fileMenu.addSeparator(); 
fileMenu.add(exitMenuItem);

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);
exitMenuItem.setAccelerator(cntrlEKey);

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.




JPopupMenu

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 
popupMenu.add(popup1); 
popupMenu.add(popup2); 
popupMenu.add(popup3);

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()  {
    @Override
    public void  mousePressed(MouseEvent e)  {
        if (e.isPopupTrigger()) {
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
    @Override
    public void  mouseReleased(MouseEvent e)  {
        if (e.isPopupTrigger()) {
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
};

// Add a  mouse listener to myComponent 
myComponent.addMouseListener(ml);