Richard G Baldwin (512) 223-4758, baldwin@austin.cc.tx.us, http://www2.austin.cc.tx.us/baldwin/

The AWT Package, Checkbox Menus

Java Programming, Lecture Notes # 142, Revised 01/27/98.

Preface

Students in Prof. Baldwin's Advanced Java Programming classes at ACC are responsible for knowing and understanding all of the material in this lesson.

Introduction

This series of lessons is concentrating on package java.awt where most of the functionality exists for providing the user interface to your application or applet.

We have learned how to handle events and use layout managers.These two topics form the basis for the design and implementation of a Graphical User Interface.

Now we are learning about the various components that we can combine with layout and event handling to produce an effective Graphical User Interface.

The available components are defined by classes in the package java.awt. Our approach is to group those classes into categories and study the material on a category basis. As of this writing, it looks as if the remaining categories are:

As things develop, it may be necessary to modify these groupings.

Menus

The inheritance hierarchy for menus is as shown below.
 
java.lang.Object
        |
        +----MenuShortcut 
        |
        +----java.awt.MenuComponent 
                |
                +----java.awt.MenuBar
                |
                +----java.awt.MenuItem 
                        |
                        +----java.awt.Menu
                        |
                        +----java.awt.CheckboxMenuItem
                        |
                        +----java.awt.PopupMenu
There are a number of interesting issues associated with menus which are being discussed in this series of documents.

Previous lessons discussed and provided sample programs for the following classes.

This lesson will discuss and and provide a sample program for A subsequent lesson will deal with: A sample program in a previous lesson made use of the Menu, MenuItem, MenuBar, and MenuShortcut classes.

This lesson will make use of the same set of classes, except this time we will substitute CheckboxMenuItem in place of MenuItem.

In addition, whereas the previous lesson used an ActionListener class to process the events generated by selecting menu items, this lesson will use an ItemListener class for processing events generated by selecting menu items.

We will defer detailed consideration of the PopupMenu class to a subsequent lesson.

A previous lesson discussed the MenuComponent, Menu, MenuItem, MenuBar, and MenuShortcut classes in detail. We won't repeat that here. We will begin our detailed discussion her with the CheckboxMenuItem class.

CheckboxMenuItem Class

The CheckboxMenuItem class is used to instantiate objects which can become the choices in a menu.

Unlike the ordinary menu items discussed in a previous lesson, these menu items behave much like checkbox components behave. An operational description of the behavior of menu items of this type is contained in the discussion of the sample program that follows.

CheckboxMenuItem has no fields and the following public constructors:

As you have probably figured out from reading the descriptions of the constructors, menu items of type CheckboxMenuItem have a boolean state value which is either true or false. Menu items of this type either do or do not display a checkmark or other visible indication of having been checked or unchecked. When such a menu item has a check mark, its state is true. Otherwise, it is false.

This class provides about nine methods, with some of the more interesting ones listed below.

The addItemListener() method is not very familiar to us. Whenever a menu item is chosen, an ItemEvent is generated. In order to cause the selection of that menu item to cause a specific action, we will instantiate and register an ItemListener object which contains an overridden itemStateChanged() method to produce the desired action.

In the case of our sample program, the desired action will simply be to display the identification and state of the menu item that was selected.

Sample Program

This program is designed to be compiled and run under JDK 1.1. It illustrates the use of checkbox menus.

This application places one menu in a Frame object. The menu contains three items of type CheckboxMenuItem. An item of this type in a menu looks pretty much like an ordinary menu item until you select it. When you select it, a checkmark or other visual indication that it has been selected appears on the menu. Selecting the item again causes the checkmark to be removed. These operations cause the "state" of the item to change. A checked item has a state of true and an unchecked item has a state of false.

Selection of an item generates an ItemEvent that can be trapped using an object of type ItemListener which overrides the method itemStateChanged(ItemEvent e).

When such an event is trapped, several pieces of important information including the new state, the item label, and the item name are contained in the ItemEvent object passed in as a parameter. This information can be used to identify which item has changed state and to implement the required action.

In this program, the action of the overridden itemStateChanged() method is to display a line of text on the screen showing the source information contained in the ItemEvent object.

Typical screen outputs for menu items being selected and deselected are shown below. Line breaks were manually inserted in this material to make it fit on the screen.
 
java.awt.CheckboxMenuItem[
  chkmenuitem0,label=First Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem1,label=Second Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem2,label=Third Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem0,label=First Item,state=false]
java.awt.CheckboxMenuItem[
  chkmenuitem1,label=Second Item,state=false]
java.awt.CheckboxMenuItem[
  chkmenuitem2,label=Third Item,state=false]
A windowClosing() event listener object is also instantiated and registered on the frame to terminate the program when the frame is closed.

The program was tested using JDK 1.1.3 running under Win95.

Interesting Code Fragments

There is some repetitious code in this sample program due to the fact that essentially the same code is required to create each menu item and register a Listener object on it.

The order that items are instantiated and associated is important. The first interesting code fragment instantiates several CheckboxMenuItem objects which will be added to a Menu object to produce a menu with several choices.

The Menu object will be added to a MenuBar object to produce a menu bar assembly with one menu.

The MenuBar object will then be associated with the Frame object.

That's the structural overview. Now let's go back to the CheckboxMeunItem objects. The following code is typical of that required to instantiate those objects.
 
   CheckboxMenuItem firstMenuItem = 
                      new CheckboxMenuItem("First Item");
The next code fragment is interesting only because it makes use of a type of Listener class that we haven't used before. The code fragment is typical of that required to instantiate and register an ItemListener object on each CheckboxMenuItem.
 
    CheckBoxMenuProcessor eventProcessor = 
                               new CheckBoxMenuProcessor();
    firstMenuItem.addItemListener(eventProcessor);
Following this, there is code to instantiate a Menu object and add the CheckboxMenuItems to it. That code is essentially the same as was used in our sample program for Ordinary Menus. Also there is similar code to add the Menu object to a MenuBar object, and code to associate the MenuBar object to the Frame object. That is also old stuff by now.

The next interesting code fragment is class that implements the ItemListener interface. Again, it is only interesting because it implements an interface that we haven't used before and overrides a method that we haven't used before. Otherwise, the code in the class definition is straightforward.
 
class CheckBoxMenuProcessor implements ItemListener{
  public void itemStateChanged(ItemEvent e){
    //Display the menu item that generated the ItemEvent
    System.out.println(e.getSource());
  }//end itemStateChanged
}//end class CheckBoxMenuProcessor
The remaining code is similar to that which you have seen in many previous example programs. A complete listing of the program is provided in the next section.

Program Listing

This section contains a complete listing of the program. See the previous sections for an operational description of the program.
 
/*File Menu03.java Copyright 1997, R.G.Baldwin
This program is designed to be compiled and run under 
JDK 1.1

Illustrates use of checkbox menus.

This application places one menu in a Frame object.  The 
menu contains three items of type CheckboxMenuItem.  An 
item of this type in a menu looks like an ordinary menu 
item until you select it.  When you select it, a checkmark
or other visual indication that it has been selected 
appears on the menu.  Selecting the item again causes the
checkmark to be removed.  These operations cause the 
"state" of the item to change.  A checked item has a state
of true and an unchecked item has a state of false.

Selection of an item generates an ItemEvent that can
be trapped using a Listener object of type ItemListener 
which overrides the method itemStateChanged(ItemEvent e).
When such an event is trapped, several pieces of important
information including the new state, the item label, and
the item name are contained in the ItemEvent object passed
in as a parameter.  This information can be used to 
identify which item has changed state and to implement the
required action.

In this program, the action of the overridden 
itemStateChanged() method is to display a line of text on
the screen showing the information contained in the 
ItemEvent object.

Typical screen outputs (with line breaks manually inserted)
when menu items are selected and deselected are:

java.awt.CheckboxMenuItem[
  chkmenuitem0,label=First Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem1,label=Second Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem2,label=Third Item,state=true]
java.awt.CheckboxMenuItem[
  chkmenuitem0,label=First Item,state=false]
java.awt.CheckboxMenuItem[
  chkmenuitem1,label=Second Item,state=false]
java.awt.CheckboxMenuItem[
  chkmenuitem2,label=Third Item,state=false]

A windowClosing() event listener object is instantiated 
and registered on the frame to terminate the program when
the frame is closed.

The program was tested using JDK 1.1.3 running under Win95.
**********************************************************/

import java.awt.*;
import java.awt.event.*;
//=======================================================//

public class Menu03 {
  public static void main(String[] args){
    GUI gui = new GUI();//instantiate a GUI
  }//end main
}//end class Menu03
//=======================================================//

class GUI {
  public GUI(){//constructor
  
    //Instantiate CheckboxMenuItem objects  
    CheckboxMenuItem firstMenuItem = 
                        new CheckboxMenuItem("First Item");
    CheckboxMenuItem secondMenuItem = 
                       new CheckboxMenuItem("Second Item");
    CheckboxMenuItem thirdMenuItem = 
                        new CheckboxMenuItem("Third Item");
     
    //Instantiate an ItemListener object and register it 
    // on the CheckboxMenuItem objects.  
    CheckBoxMenuProcessor eventProcessor = 
                               new CheckBoxMenuProcessor();
    firstMenuItem.addItemListener(eventProcessor);
    secondMenuItem.addItemListener(eventProcessor);
    thirdMenuItem.addItemListener(eventProcessor);
    
    //Instantiate a Menu object and add the 
    // CheckboxMenuItem objects to it
    Menu menuA = new Menu("Menu A");
    menuA.add(firstMenuItem);
    menuA.add(secondMenuItem);
    menuA.add(thirdMenuItem);    
    
    //Instantiate a MenuBar object and add the Menu 
    // objects to it  
    MenuBar menuBar = new MenuBar();
    menuBar.add(menuA);  
  
    //Instantiate a Frame object and associate the MenuBar
    // object with the Frame object.  Note that this is 
    // NOT a typical myFrame.add() method invocation, but
    // rather is a special form of method invocation that
    // is required to associate a MenuBar object with a
    // Frame object.
    Frame myFrame = 
                  new Frame("Copyright 1997, R.G.Baldwin");
    myFrame.setMenuBar(menuBar);
    myFrame.setSize(250,100);
    myFrame.setVisible(true);

    //Instantiate and register a window listener to 
    // terminate the program when the Frame is closed. 
    myFrame.addWindowListener(new Terminate());
  }//end constructor
}//end class GUI definition
//=======================================================//

//Class to instantiate an ItemListener object to be 
// registered on the menu items.
class CheckBoxMenuProcessor implements ItemListener{
  public void itemStateChanged(ItemEvent e){
    //Display the menu item that generated the ItemEvent
    System.out.println(e.getSource());
  }//end itemStateChanged
}//end class CheckBoxMenuProcessor
//=======================================================//

class Terminate extends WindowAdapter{
  public void windowClosing(WindowEvent e){
    System.exit(0);//terminate the program
  }//end windowClosing
}//end class Terminate
//=======================================================//
-end-