Header javaperspective.com

5.18. Menus
Last updated: 25 January 2013.

This tutorial will show you how to use menus in Java.

As you might already know, a menu displays a set of selectable items on demand. A menu can be bound to a menu bar and appear when the user clicks the menu bar or, alternatively, it can be a popup menu that appears when the user right-clicks a component.


5.18.1. How to make a menu bar

A menu bar is an instance of the class JMenuBar. The method setJMenuBar(JMenuBar menubar) sets the specified menu bar to a container. Typically, a JMenuBar object contains JMenu objects. Each JMenu object may contain JMenuItem objects, other JMenu objects (the sub menus), JCheckBoxMenuItem objects and JRadioButtonMenuItem objects. The following picture shows a frame with a menu bar containing 3 menus named JMenu 1, JMenu 2 and JMenu 3:


Menu bar


Apart from JMenuBar, the core classes involved in building the menu bar shown above are JMenu, JMenuItem, JCheckBoxMenuItem and JRadioButtonMenuItem. Given that these classes are subclasses of the class AbstractButton, they have all the features provided by buttons. Therefore, you can bind icons, keyboard shortcuts and tooltip texts to menu items. The code follows:


import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.ButtonGroup;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;

public final class MenuBars extends JFrame implements ActionListener, ItemListener {

   
private JMenuItem menuItem1;
   
private JMenuItem menuItem2;
   
private JMenuItem menuItem3;
   
private JMenuItem menuItem4;
   
private JMenuItem menuItem5;
   
private JMenuItem menuItem6;

   
private JCheckBoxMenuItem checkBoxMenuItem1;
   
private JCheckBoxMenuItem checkBoxMenuItem2;
   
private JCheckBoxMenuItem checkBoxMenuItem3;

   
private JRadioButtonMenuItem radioButtonMenuItem1;
   
private JRadioButtonMenuItem radioButtonMenuItem2;
   
private JRadioButtonMenuItem radioButtonMenuItem3;

   
private JLabel label;


   
public MenuBars(){
         
init();
          setMenu
();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
public void actionPerformed(ActionEvent e){
         
Object source = e.getSource();

         
if(source.equals(menuItem1) || source.equals(menuItem2)
                     
|| source.equals(menuItem3) || source.equals(menuItem4)
                     
|| source.equals(menuItem5) || source.equals(menuItem6)){

               
label.setText(((JMenuItem) source).getText() + " clicked");
         
}
         
else if(source.equals(radioButtonMenuItem1)
                     
|| source.equals(radioButtonMenuItem2)
                     
|| source.equals(radioButtonMenuItem3)){

               
label.setText(((JRadioButtonMenuItem) source).getText() + " clicked");
         
}
    }


   
private void addComponents(){
         
label = new JLabel();
          label.setHorizontalAlignment
(SwingConstants.CENTER);
          add
(label);
   
}


   
private void init(){
         
try{
               
UIManager.setLookAndFeel(UIManager.getCrossPlatformLookAndFeelClassName());
         
}
         
catch(Exception e){
               
e.printStackTrace();
         
}

         
setTitle("MenuBars");
          setSize
(500, 300);
          setLocationRelativeTo
(null);
   
}


   
public void itemStateChanged(ItemEvent e){
         
Object source = e.getSource();

         
if(source.equals(checkBoxMenuItem1)
                     
|| source.equals(checkBoxMenuItem2)
                     
|| source.equals(checkBoxMenuItem3)){

               
if(e.getStateChange() == ItemEvent.SELECTED)
                     
label.setText(((JCheckBoxMenuItem) source).getText() + " selected");
               
else
                     
label.setText(((JCheckBoxMenuItem) source).getText() + " deselected");
         
}
    }


   
private void setMenu(){
         
JMenuBar menuBar = new JMenuBar();

         
// Create the first JMenu and add it to menuBar
         
JMenu menu1 = new JMenu("JMenu 1");
          menuBar.add
(menu1);

         
// Add a JMenuItem to menu1
         
menuItem1 = new JMenuItem("JMenuItem 1");
          menuItem1.addActionListener
(this);
          menu1.add
(menuItem1);

         
// Add another JMenuItem to menu1
         
menuItem2 = new JMenuItem("JMenuItem 2");
          menuItem2.addActionListener
(this);
          menu1.add
(menuItem2);

         
// Add another JMenuItem to menu1
         
menuItem3 = new JMenuItem("JMenuItem 3");
          menuItem3.addActionListener
(this);
          menu1.add
(menuItem3);

         
// Add a separator to menu1
         
menu1.addSeparator();

         
// Create a sub menu
         
JMenu subMenu = new JMenu("JMenu sub menu");

         
// Add a JMenuItem to subMenu
         
menuItem4 = new JMenuItem("JMenuItem 4");
          menuItem4.addActionListener
(this);
          subMenu.add
(menuItem4);

         
// Add another JMenuItem to subMenu
         
menuItem5 = new JMenuItem("JMenuItem 5");
          menuItem5.addActionListener
(this);
          subMenu.add
(menuItem5);

         
// Add another JMenuItem to subMenu
         
menuItem6 = new JMenuItem("JMenuItem 6");
          menuItem6.addActionListener
(this);
          subMenu.add
(menuItem6);

         
// Add subMenu to menu1
         
menu1.add(subMenu);

         
// Add a separator to menu1
         
menu1.addSeparator();

         
// Add a JCheckBoxMenuItem to menu1
         
checkBoxMenuItem1 = new JCheckBoxMenuItem("JCheckBoxMenuItem 1");
          checkBoxMenuItem1.addItemListener
(this);
          menu1.add
(checkBoxMenuItem1);

         
// Add another JCheckBoxMenuItem to menu1
         
checkBoxMenuItem2 = new JCheckBoxMenuItem("JCheckBoxMenuItem 2");
          checkBoxMenuItem2.addItemListener
(this);
          menu1.add
(checkBoxMenuItem2);

         
// Add another JCheckBoxMenuItem to menu1
         
checkBoxMenuItem3 = new JCheckBoxMenuItem("JCheckBoxMenuItem 3");
          checkBoxMenuItem3.addItemListener
(this);
          menu1.add
(checkBoxMenuItem3);

         
// Add a separator to menu1
         
menu1.addSeparator();

         
// Add a JRadioButtonMenuItem to menu1
         
radioButtonMenuItem1 = new JRadioButtonMenuItem("JRadioButtonMenuItem 1");
          radioButtonMenuItem1.addActionListener
(this);
          menu1.add
(radioButtonMenuItem1);

         
// Add another JRadioButtonMenuItem to menu1
         
radioButtonMenuItem2 = new JRadioButtonMenuItem("JRadioButtonMenuItem 2");
          radioButtonMenuItem2.addActionListener
(this);
          menu1.add
(radioButtonMenuItem2);

         
// Add another JRadioButtonMenuItem to menu1
         
radioButtonMenuItem3 = new JRadioButtonMenuItem("JRadioButtonMenuItem 3");
          radioButtonMenuItem3.addActionListener
(this);
          menu1.add
(radioButtonMenuItem3);

         
// Add the JRadioButtonMenuItems to a ButtonGroup
         
ButtonGroup buttonGroup = new ButtonGroup();
          buttonGroup.add
(radioButtonMenuItem1);
          buttonGroup.add
(radioButtonMenuItem2);
          buttonGroup.add
(radioButtonMenuItem3);


         
// Create the second JMenu and add it to menuBar
         
JMenu menu2 = new JMenu("JMenu 2");
          menuBar.add
(menu2);

         
// Create the third JMenu and add it to menuBar
         
JMenu menu3 = new JMenu("JMenu 3");
          menuBar.add
(menu3);


         
// Set the menu bar of this JFrame
         
setJMenuBar(menuBar);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new MenuBars();
               
}
          })
;
   
}
}

The JFrame contains a single component: a label that displays the current state of the last selected item in the menu bar. For example, if you select JMenuItem 1 in the menu bar, the following message is displayed in the label: JMenuItem 1 clicked. That is achieved by registering a listener for each item of the menu. In the code above, the method addActionListener is called upon all the JMenuItem and JRadioButtonMenuItem objects in order to handle the clicks on those items. Similarly, the method addItemListener is called upon all the JCheckBoxMenuItem objects in order to handle the state changes of the checkbox menu items. The code that is executed when an item is selected is in the methods actionPerformed(ActionEvent e) and itemStateChanged(ItemEvent e).


5.18.2. How to make a popup menu

A popup menu is an on-demand menu that is bound to a component in a GUI. It is triggered by a mouse event that is look and feel specific. On certain L&Fs, simply right-clicking the associated component displays a popup menu that stays visible. On other L&Fs, the popup is visible as long as the right mouse button is pressed and disappears when it is released.

A popup menu is an instance of the class JPopupMenu to which menu items are added. Building a popup menu consists in registering upon a component a mouse listener that responds to popup menu trigger events. The picture shown below is a frame containing a label that is associated with a popup menu:


Popup menu



Here is the code:


import java.awt.Dimension;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.border.BevelBorder;

public final class PopupMenus extends JFrame {


   
private JPopupMenu popupMenu;

   
public PopupMenus() {
         
init();
          addComponents
();

          setDefaultCloseOperation
(JFrame.EXIT_ON_CLOSE);
          setVisible
(true);
   
}


   
private class PopupMenuListener extends MouseAdapter {
         
public void mousePressed(MouseEvent e) {
               
displayPopup(e);
         
}

         
public void mouseReleased(MouseEvent e) {
               
displayPopup(e);
         
}

         
private void displayPopup(MouseEvent e) {
               
if(e.isPopupTrigger()) // the event must be the popup menu trigger event for this platform.
                     
popupMenu.show(e.getComponent(), e.getX(), e.getY());
         
}
    }


   
private void addComponents() {
         
// Create the content pane
         
JPanel contentPane = new JPanel();


         
// Create the popup menu and add menu items to it
         
popupMenu = new JPopupMenu();

          JMenuItem menuItem1 =
new JMenuItem("JMenuItem 1");
          popupMenu.add
(menuItem1);

          JMenuItem menuItem2 =
new JMenuItem("JMenuItem 2");
          popupMenu.add
(menuItem2);

          JMenuItem menuItem3 =
new JMenuItem("JMenuItem 3");
          popupMenu.add
(menuItem3);


         
// Create the label and register a mouse listener upon it
         
JLabel label = new JLabel();
          label.setHorizontalAlignment
(SwingConstants.CENTER);
          label.setPreferredSize
(new Dimension(130, 30));
          label.setBorder
(BorderFactory.createBevelBorder(BevelBorder.LOWERED));
          label.setText
("Right-click me");
          label.addMouseListener
(new PopupMenuListener());


         
// Add the label to the content pane
         
contentPane.add(label);

         
// Add the content pane to the JFrame
         
add(contentPane);
   
}


   
private void init() {
         
setTitle("PopupMenus");
          setSize
(300, 150);
          setLocationRelativeTo
(null);
   
}


   
public static void main(String[] args){
         
SwingUtilities.invokeLater(new Runnable() {
               
public void run() {
                     
new PopupMenus();
               
}
          })
;
   
}
}

Of course, nothing happens if you select a menu item since no action listener was registered for any menu item. You can register action listeners for the menu items in the popup menu as I registered action listeners for the menu items shown in the first section (5.18.1).


You are here :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.18. Menus
Next tutorial :  JavaPerspective.com  >   Intermediate Tutorials  >   5. Graphical User Interfaces  >   5.19. Tool bars

Copyright © 2013 - 2016. JavaPerspective.com. All rights reserved.  ( Terms | Contact | About ) 
Java is a trademark of Oracle Corporation
Image 1 Image 2 Image 3 Image 4 Image 5 Image 6 Image 7