Menus and submenus

 

Overview

A menu bar having multiple menus (each with multiple menu items, pop-up submenus, checkbox menu items, and separators) can be applied to any container that extends the Frame class. Note that other Window subclasses (such as Dialog) and Panel subclasses (such as Applet) cannot contain a menu bar.

To work with menus and submenus, you need to know the following classes:

MenuComponent
MenuBar
Menu
MenuItem
CheckboxMenuItem

 

The MenuComponent class 

Object

\

MenuComponent

 

The MenuBar class 

Object

\

MenuComponent

 

\

MenuBar

MenuBar mainBar = new MenuBar(); 
appFrame.setMenuBar(mainBar);

When initially constructed, mainbar has no menus. Its add() method may be called to add them. Other methods exist, but are of little general use.

 

The Menu class 

Object

\

MenuComponent

   

\

MenuItem

\

Menu

Menu fileMenu = new Menu("File"); 
mainBar.add(fileMenu);

When initially constructed, fileMenu has no submenus, menu items, or checkbox menu items. Its add() method may be called to add them. The order in which menu items appear will be the order in which they are added.

Method

Usage

add()

Adds the specified MenuItem to the menu

addSeparator()

Adds a separator line to the menu at the current position

Consult the help facility of your Java development environment or the Java API for more details.

 

The MenuItem class 

Object

\

MenuComponent

 

\

MenuItem

MenuItem open = new MenuItem("Open"); 
open.addActionListener(this); 
fileMenu.add(open);

Method

Usage

addActionListener()

Adds the specified ActionListener to receive ActionEvent objects from this menu item

getActionCommand()

Returns the command name of the action event fired by this menu item

getLabel()

Gets the label of this menu item

isEnabled()

Determines whether the menu item is enabled

removeActionListener()

Removes the specified action listener so it no longer receives ActionEvent objects from this menu item

setActionCommand()

Sets the command name for the ActionEvent objects fired by this menu item

setEnabled()

Enables or disables the menu item

setLabel()

Sets the label of this menu item

Consult the help facility of your Java development environment or the Java API for more details.

 

The CheckboxMenuItem class 

Object

\

MenuComponent

   

\

MenuItem

\

CheckboxMenuItem

CheckboxMenuItem autoSave = new CheckboxMenuItem("Auto Save");
autoSave.addItemListener(this);
fileMenu.add(autoSave);

By default, the initial state of a CheckboxMenuItem is "off". An overloaded constructor may be used to initialize the object to be "on".

Method

Usage

addItemListener()

Adds the specified ItemListener to receive ItemEvent objects from this checkbox menu item

getState()

Determines whether the state of this checkbox menu item is "on" or "off"

removeItemListener()

Removes the specified item listener so it no longer receives ItemEvent objects from this checkbox menu item

setState()

Sets the check box menu item to the specified state

Consult the help facility of your Java development environment or the Java API for more details.

Example:

import java.awt.*;
import java.awt.event.*;

public class App extends Frame implements WindowListener,
  ActionListener, ItemListener {

  // References for menu components

  MenuBar mainBar;
  Menu fileMenu;
  MenuItem exit;
  Menu viewMenu;
  Menu sizeSubmenu;
  MenuItem large;
  MenuItem medium;
  MenuItem small;
  CheckboxMenuItem bold;
  CheckboxMenuItem italics;

  // Message to be displayed and its initial font

  Label message = new Label("Hello World!");
  Font myFont = new Font("SanSerif", Font.PLAIN, 24);

  public static void main(String[] args) {
    App myWindow = new App("A stylish menu");
    myWindow.setSize(300,200);
    myWindow.setVisible(true);
  }

  public App(String title) {
    super(title);
    setLayout(new BorderLayout());
    addWindowListener(this);

    // Create and set the frame's menu bar (unpopulated)

    mainBar = new MenuBar();
    setMenuBar(mainBar);

    // Create the "File" menu and add it to the frame's menu bar

    fileMenu = new Menu("File");
    fileMenu.addSeparator();
    exit = new MenuItem("Exit");
    exit.addActionListener(this);
    fileMenu.add(exit);
    mainBar.add(fileMenu);

    // Build the "Text Size" submenu in order to reference it shortly

    sizeSubmenu = new Menu("Text Size");
    large = new MenuItem("Large");
    large.addActionListener(this);
    sizeSubmenu.add(large);
    medium = new MenuItem("Medium");
    medium.addActionListener(this);
    sizeSubmenu.add(medium);
    small = new MenuItem("Small");
    small.addActionListener(this);
    sizeSubmenu.add(small);

    // Create the "View" menu and add it to the frame's menu bar

    viewMenu = new Menu("View");
    viewMenu.add(sizeSubmenu);
    viewMenu.addSeparator();
    bold = new CheckboxMenuItem("Bold");
    bold.addItemListener(this);
    viewMenu.add(bold);
    italics = new CheckboxMenuItem("Italics");
    italics.addItemListener(this);
    viewMenu.add(italics);
    mainBar.add(viewMenu);

    // Set the message in the frame

    message.setFont(myFont);
    message.setBackground(Color.black);
    message.setForeground(Color.white);
    message.setAlignment(Label.CENTER);
    add(message);
  }

  public void actionPerformed(ActionEvent e) {
    if (e.getSource().equals(exit)) {
      dispose();
      System.exit(0);
    }
    else {
      if (e.getSource().equals(large)) {
        myFont = new Font(myFont.getFontName(), myFont.getStyle(), 36);
      }
      if (e.getSource().equals(medium)) {
        myFont = new Font(myFont.getFontName(), myFont.getStyle(), 24);
      }
      if (e.getSource().equals(small)) {
        myFont = new Font(myFont.getFontName(), myFont.getStyle(), 12);
      }
      message.setFont(myFont);
    }
  }

  public void itemStateChanged(ItemEvent e) {
    if (e.getSource().equals(bold)) {
      if (bold.getState() == true) {
        myFont = new Font(myFont.getFontName(),
          myFont.getStyle() + Font.BOLD, myFont.getSize());
      }
      else {
        myFont = new Font(myFont.getFontName(),
          myFont.getStyle() - Font.BOLD, myFont.getSize());
      }
    }
    if (e.getSource().equals(italics)) {
      if (italics.getState() == true) {
        myFont = new Font(myFont.getFontName(),
          myFont.getStyle() + Font.ITALIC, myFont.getSize());
      }
      else {
        myFont = new Font(myFont.getFontName(),
          myFont.getStyle() - Font.ITALIC, myFont.getSize());
      }
    }
    message.setFont(myFont);
  }

  public void windowClosing(WindowEvent e) {
    dispose();
    System.exit(0);
  }

  public void windowOpened(WindowEvent e) {}
  public void windowActivated(WindowEvent e) {}
  public void windowIconified(WindowEvent e) {}
  public void windowDeiconified(WindowEvent e) {}
  public void windowDeactivated(WindowEvent e) {}
  public void windowClosed(WindowEvent e) {}
}

Notes:

  1. The class implements the ActionListener interface in order to handle the selection of menu items and the ItemListener interface in order to handle the selection of checkbox menu items

  2. Within the application's constructor, the order of instantiation is critical. The main menu bar (mainBar) must exist before a menu (such as fileMenu) may be added to it. Similarly, the "Text Size" submenu (sizeSubmenu) is built prior to adding it to the "View" menu (viewMenu). Also notice that each MenuItem object has a registered ActionListener and each CheckboxMenuItem object has a registered ItemListener.

  3. The actionPerformed() method begins by testing for the "Exit" menu selection. If it was chosen, the application is immediately terminated. Otherwise, a determination is made as to which text size the user selected, a new font is created to meet their request, and the new font is applied to the message being displayed.

  4. The itemStateChanged() method determines which CheckboxMenuItem was chosen (bold or italics), creates a new font to meet their request, and applies it to the message being displayed.

 

Review questions

  1. Which of the following may a menu contain?  (choose two)

  1. a List object

  1. a separator

  2. a Menu object

  3. a Checkbox object

  4. a Panel object

  1. Which of the following may contain a menu bar?

  1. Applet

  1. Canvas

  2. Panel

  3. Dialog

  4. none of the above

  1. Code a single statement to create a checkbox menu item named gridLines with a label of "Grid Lines" and initially set to the "on" state.

  1. If someItem is a MenuItem object, which one of the following can legally replace the XXXXX in the following statement?

someItem.addXXXXXListener(this);

  1. Action

  2. Item

  3. MenuAction

  4. MenuItem

  5. both A and B