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

The AWT Package, The Button, Checkbox, Choice, and List Classes

Java Programming, Lecture Notes # 132, Revised 01/05/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.

This lesson, and the next several lessons will concentrate on the use of the GUI components available in the JDK 1.1.x release. You should also be aware that an entirely new set of lightweight GUI components, known collectively as the Swing set, are in the pre-beta evaluation stage at JavaSoft as of January 1998.

It is rumored that JDK 1.2 (or perhaps 2.0) will be released in the first or second quarter of 1998, and that the Swing components will be part of that release.

The Swing components are not intended to replace the AWT components from JDK 1.1, but rather are intended to supplement those components with a set of components that provide a consistent look and feel across all platforms. In addition to providing a consistent look and feel, several components (such as progress bars) are included in the Swing set that are not included in the JDK 1.1 AWT.

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 we have learned how to use the layout managers. These two topics form the basis for the design and implementation of a Graphical User Interface.

The next step is to take a look at the variety of components that are available to 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 will be to group those classes into categories and study the material on a category basis. A previous lesson discussed a set of classes that we referred to as the Container Classes.

As of this writing, it looks as if the remaining categories to be discussed will be:

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

This lesson will concentrate on the Non-Text Input classes.

The Non-Text Input Classes

The components in this group are generally used to allow the user to input information to the program without the requirement to use the keys on the keyboard. In some circumstances they could also be used to output information to the user as well but that is not common practice.

The first four of the following five classes extend the class Component.

The class named CheckboxGroup does not extend Component, but extends Object instead. As the name suggests, objects of this class can be used to group CheckBox components so that they behave in a mutually exclusive fashion.

Button

We have been using Button objects since the beginning of the course. However, we have never stopped to consider their attributes. We will take a close look at the Button class now so that we will better understand what we are doing when we use a Button object in the future.

To begin with, the Button class extends Component which causes it to have access to the many dozens of methods defined in the Component class. To quote the JDK 1.1 documentation, the Button class is
"A class that produces a labeled button component."
As of 3/12/97, the Button class has the following two public constructors:

We have typically used the second version of the constructor which accepts a String object as the label for the button.

The Button class has no fields or instance variables. As of 3/12/97, it has ten methods including the following familiar methods which we have used in previous lessons.

In addition to these ten methods, it also inherits all the methods of the Component class and the Object class.

ActionListener is one of the high-level or semantic events. An action event is generated when we click on a Button object.

We also learned during our studies of event handling in JDK 1.1 that an object of the Button class can generate low-level events such as mouse events, focus events, etc, because it inherits methods, such as the following, from the Component class.

In fact, objects of all subclasses of Component can generate the low-level events in the above list.

We have worked with many different sample programs containing Button objects, so there isn't any need to write a program for the sole purpose of studying the Button class. In addition, some of the later sample programs in this lesson will make use of the Button class.

Checkbox

If you have ever worked much with Windows, you are probably familiar with objects of the Checkbox class. However, we have not made much use of objects of this class in our previous lessons.

The Checkbox class extends the Component class, and implements the ItemSelectable interface.

According to the JDK 1.1 documentation, the ItemSelectable interface is
"The interface for objects which contain a set of items for which zero or more can be selected."
The ItemSelectable interface declares the following three methods, meaning that they must be defined by the Checkbox class since it implements the interface.

As of 3/12/97, the Checkbox class has no fields. It has the following five constructors. The last two appear to be functionally the same except that the position of two arguments is switched between the two.

As of 3/12/97, the Checkbox class has about a dozen methods, including the three listed above under the discussion of the ItemSelectable interface. We will use methods from this class in a sample program that follows later.

Before getting to that sample program, we need to understand the class named CheckboxGroup. According to the JDK 1.1 documentation,
"This class is used to create a multiple-exclusion scope for a set of Checkbox buttons. For example, creating a set of Checkbox buttons with the same CheckboxGroup object means that only one of those Checkbox buttons will be allowed to be "on" at a time."
As of 3/12/97, this class had no fields and only one constructor:

Although there were five methods, two were deprecated leaving the following three:

Sample Checkbox Program

Programming Checkbox objects can be simple, or it can be complicated, depending on your approach.

The simple way to process Checkbox objects is to put the mutually-exclusive Checkbox objects in a CheckboxGroup, ignore all the events that are generated as the user selects individual Checkbox objects, and then process a single Action event when the user has made his choice and clicks an "OK" Button object. A very large percentage of programs that are written to work in a Windows environment are designed this way.

The complicated way to process Checkbox objects is to respond to the different kinds of events that are generated as the user selects different Checkbox objects. Actually, responding to the events is not complicated, because we can still use the Source/Listener approach of instantiating Listener objects and registering them on the Checkbox objects.

The complicated part is implementing the logic needed to make sense out of the user activity, particularly when the user may be prone to change his or her mind regarding the selection and we need to deal with that situation.

In this lesson, we will discuss a sample program that does it the simple way. We will let the user change her mind as many times as needed and click as many checkboxes as required before finally making a decision and clicking an OK Button object.

The program places four Checkbox objects and a Button object in a Frame object. The Checkbox objects are defined to be in a CheckBoxGroup object when they are instantiated. They are labeled A, B, C, and D.

An ActionListener object is instantiated and registered on the Button object.

Because the Checkbox objects are in a group, only one can be selected at any time.

The action to deselect a previously-selected Checkbox object when a different Checkbox object is selected is handled automatically with no effort required by the programmer other than to put them in a CheckboxGroup.

The Button object can be clicked at any time causing the overridden actionPerformed() method in the ActionListener object to determine and display the identification of the Checkbox object that is currently selected.

Both the unique component name assigned by the system and the label assigned by the programmer are displayed, demonstrating that you can use either form of identification in your programs.

The following outputs were produced by clicking the Button object while each one of the four Checkbox objects was selected.

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 running under Win95.

Interesting Code Fragments for Checkbox Program

The first step is to create a CheckboxGroup object which is later used to group the four Checkbox objects into a single logical group.
 CheckboxGroup myCheckboxGroup = new CheckboxGroup();
Then we create a Button object to serve as our "OK" button. We also create an ActionListener object and register it on the Button object.
Button myButton = new Button("OK");

myButton.addActionListener(

              new MyActionListener(myCheckboxGroup));
The following code is typical of that used to instantiate the four Checkbox objects as a part of the group named myCheckBoxGroup and add them to the Frame object. We will skip the instantiation of the Frame object, setting the layout manager, and adding the Button object to the Frame because you have seen how to do that many times already.
myFrame.add(new Checkbox("A",true, myCheckboxGroup));
The next code fragment is the overridden actionPerformed() method in the ActionListener object that extracts the identification of the currently selected Checkbox object.
  public void actionPerformed(ActionEvent e){

    System.out.println(

      aCheckBoxGroup.getSelectedCheckbox().getName()+

      " " + 

      aCheckBoxGroup.getSelectedCheckbox().getLabel());

  }//end actionPerformed()
The getSelectedCheckbox() method is a member of the CheckboxGroup class. This method returns an object of type Checkbox. The getLabel() method is a member of the Checkbox class. The getName() method is a member of the Component class, which is a superclass of Checkbox.

Program Listing for Checkbox Program

A listing of the entire program with additional comments follows. See the previous sections for a operational description of the program.
/*File Checkbox01.java Copyright 1997, R.G.Baldwin



The following output was produced by clicking the Button 

object while each of the four buttons was selected.



checkbox0 A

checkbox1 B

checkbox2 C

checkbox3 D



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.*;

import java.util.*;

//=======================================================//

public class Checkbox01 {

  public static void main(String[] args){

    //instantiate a Graphical User Interface object

    GUI gui = new GUI();

  }//end main

}//end class Checkbox01

//=======================================================//



class GUI {

  public GUI(){//constructor



    //Create a CheckboxGroup object

    CheckboxGroup myCheckboxGroup = new CheckboxGroup();



    //Create a Button object and register an ActionListener

    //  object on it

    Button myButton = new Button("OK");

    myButton.addActionListener(

                    new MyActionListener(myCheckboxGroup));

    

    //Create a Frame object to contain CheckBox objects and

    // a Button object, set to FlowLayout, add the 

    // CheckBox and Button objects, set the size and make

    // it visible.

    Frame myFrame = new Frame(

                            "Copyright 1997, R.G.Baldwin");

    myFrame.setLayout(new FlowLayout());    

    myFrame.add(new Checkbox("A",true, myCheckboxGroup));

    myFrame.add(new Checkbox("B",false,myCheckboxGroup));

    myFrame.add(new Checkbox("C",false,myCheckboxGroup));

    myFrame.add(new Checkbox("D",false,myCheckboxGroup));

    myFrame.add(myButton);

    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 display which checkbox is selected at the time

// that the OK button is pressed.

class MyActionListener implements ActionListener{

  CheckboxGroup aCheckBoxGroup;



  MyActionListener(CheckboxGroup checkBoxGroupIn){

    aCheckBoxGroup = checkBoxGroupIn;

  }//end constructor  

  

  public void actionPerformed(ActionEvent e){

    System.out.println(

       aCheckBoxGroup.getSelectedCheckbox().getName()+

        " " + 

         aCheckBoxGroup.getSelectedCheckbox().getLabel());

  }//end actionPerformed()



}//end MyActionListener

//=======================================================//



class Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate

//=======================================================//
Next, we will investigate how to create components of the Choice class.

Choice

Like Checkbox, the Choice class extends the Component class and implements the ItemSelectable interface. According to the JDK 1.1 documentation:
"The Choice class is a pop-up menu of choices. The current choice is displayed as the title of the menu."
Also, and very important for event handling, the Choice class provides the following method: This is the method that we will use for event handling in our sample program for the Choice class. Note that some books indicate that the Choice class supports the addActionListener() method, but that does not seem to be the case for JDK 1.1.
Author's Comment: In my opinion, the use of the terminology "pop-up menu" in the description above is a poor choice of words. I think of a pop-up menu as a menu that is normally invisible and becomes visible in its entirety whenever the user takes some specific action (like often happens when the user clicks the right mouse button on an object in Win95). The Choice object is more like what other IDEs might call a list box that operates like a pull-down menu. It may or may not be visible at any given point in time, but when it is visible, you must select it to cause it to pull down like a window shade and display the list of choices that it contains. In any event, you can compile and execute the program and decide what you think.
.As of 3/12.97, the Choice class has no fields and only one public constructor: Also as of 3/12/97, the Choice class has about twenty methods. Many of these methods have to do with adding and/or removing items from the menu and determining which choice has been selected by the user. We will use some of the methods in a sample program later.

A partial list of the methods of this class is reproduced below to illustrate the various ways to add items to the list of choices and various ways to deal with choices made by the user.

The use of the Choice object is illustrated in the following sample program.

Sample Program for Choice

This program is designed to be compiled and run under JDK 1.1

The program places a Choice object in a Frame object. Three String objects are added to the Choice object:

The String object "Second Choice" is selected for initial display at program startup.

An ItemListener object is instantiated and registered on the Choice object. The purpose of the ItemListener object is to identify and display the String object that is chosen whenever the user makes a choice.

Whenever the user selects a choice, an event is trapped in the overridden itemStateChanged() method of the ItemListener object. Code in the overridden method uses the getSelectedItem() method of the Choice class to identify and display the String object chosen.

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 running under Win95.

Interesting Code Fragments for Choice Program

The following code fragment is typical of that used to instantiate a Choice object and add String objects to the Choice object.
    Choice myChoice = new Choice();

    myChoice.add("First Choice");

    ...
The following statement is used to cause the String object "Second Choice" to be visible at startup.
myChoice.select("Second Choice");
The following statement is used to instantiate and register an ItemListener object on the Choice object.
myChoice.addItemListener(new MyItemListener(myChoice));
This is followed by code to create a Frame object and place the Choice object in the Frame, etc. By this point, you have seen many instances of code of this type, so we will skip over it in this discussion of interesting code fragments.

The next interesting code fragment is the overridden itemStateChanged() method in the Itemlistener object.
    public void itemStateChanged(ItemEvent e){

      System.out.println(aChoice.getSelectedItem());

    }//end itemStateChanged()
This event occurs whenever the user makes a choice (pulls down the menu and clicks on an item). As you can see, the getSelectedItem() method of the Choice class is used to obtain a String representation of the item that was selected.

Program Listing for Choice Program

A complete program listing with additional comments follows. See the previous sections for an operational description of the program.
/*File Choice01.java Copyright 1997, R.G.Baldwin



The program was tested using JDK 1.1.3 running under Win95.

**********************************************************/



import java.awt.*;

import java.awt.event.*;

import java.util.*;

//=======================================================//

public class Choice01 {

  public static void main(String[] args){

    //instantiate a Graphical User Interface object

    GUI gui = new GUI();

  }//end main

}//end class Choice01

//=======================================================//



class GUI {

  public GUI(){//constructor



    //Instantiate a Choice object and place some String 

    // objects in it.

    Choice myChoice = new Choice();

    myChoice.add("First Choice");

    myChoice.add("Second Choice");

    myChoice.add("Third Choice");



    //Select the "Second Choice" String object for display

    // at startup.    

    myChoice.select("Second Choice");



    //Instantiate and register an ItemListener object on 

    // the Choice object.    

    myChoice.addItemListener(new MyItemListener(myChoice));

    

    //Place the Choice object in a Frame object for display

    Frame myFrame = new Frame(

                            "Copyright 1997, R.G.Baldwin");

    myFrame.setLayout(new FlowLayout());    

    myFrame.add(myChoice);

    myFrame.setSize(250,150);

    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 listen for ItemListener events on the Choice

  // object

  class MyItemListener implements ItemListener{

    Choice aChoice;

    

    MyItemListener(Choice inChoice){//constructor

      aChoice = inChoice;//save a reference

    }//end constructor

    

    //Override the itemStateChanged() method of the 

    // ItemListener interface.

    public void itemStateChanged(ItemEvent e){

      System.out.println(aChoice.getSelectedItem());

    }//end itemStateChanged()

  }//end class MyItemListener

//=======================================================//



class Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate

//=======================================================//
The next topic for consideration in this lesson is the List class.

List

As with the two previous classes that we have discussed, the List class extends the Component class and implements the ItemSelectable interface.

The List class is described in the documentation as:
"A scrolling list of text items."
The List class also supports the addActionListener() method which is the method that we will use for our sample program on the List class. An ActionEvent is generated when the user double-clicks on an item in the list.

As of 3/12/97, the List class has no fields and has the following three public constructors:

As of 3/12/97, the List class provided about fifty different methods, primarily for use in manipulating the items in the list and for dealing with the situation when the user selects one or more items from the list. Some of those methods were marked deprecated. We will use a couple of methods from the List class later in our sample program.

The following is a partial list of methods in the class.

Note that there is no difference in the descriptions for add(String) and addItem(String). There is also no difference in the descriptions for add(String,int) and addItem(String,int). Even the longer descriptions provided deeper in the documentation package makes no distinction between these apparently duplicated methods.

Sample Program for List Class

This program is designed to be compiled and run under JDK 1.1

The program places a List object and a Button object in a Frame object. Fifteen String objects are added to the List object.

The second String object in the list is initially selected by the code in the program to illustrate that software selection of an item in a List object is possible.

An ActionListener object is instantiated and registered on the List object. The purpose of the ActionListener object is to identify and display the String object that is selected whenever the user makes a choice by selecting and double-clicking an item in the list.

Whenever the user selects and then double-clicks an item in the list, an event is trapped in the overridden actionPerformed() method of the ActionListener object. Code in the overridden method uses the getSelectedItem() method of the List class to identify and display the String object chosen. However, if the user double-clicks on an item while more than one item is selected, the getSelectedItem() returns null and nothing is displayed by the event handler.

A Button object is also added to the Frame object to service the case of multiple selections in the List object. An ActionListener object is registered on the Button object. Whenever the user clicks the Button object, the ActionListener object traps an ActionEvent object, identifies, and then displays the selected items in the list, even if only one item is selected. If no items are selected at that time, nothing is displayed.

A typical series of output lines from this program might be as follows:

Single Item Selection

  List Item 1

Multiple Item Selection

  List Item 1

Multiple Item Selection

  List Item 1

  List Item 3
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 running under Win95.

Interesting Code Fragments for List Class Program

The first interesting code fragment instantiates a List object and places fifteen String objects in the list. Then the list is defined to allow multiple selections. Finally, the second item in the list is initially selected by the program code so that it will be selected upon program startup.
List myList = new List();

for(int cnt = 0; cnt < 15; cnt++)

  myList.add("List Item " + cnt);

myList.setMultipleMode(true);//allow multiple selections

myList.select(1);//display item[1] on startup
The next interesting code fragment instantiates and registers an ActionListener object on the List object which will respond whenever the user double-clicks on an item in the list.
myList.addActionListener(new MyListActionListener(myList));
After this, a Button object is instantiated, an ActionListener object is instantiated and registered on the Button object, and both the List object and the Button object are added to a Frame object. However, we have seen code like this so often that it no longer falls in the category of Interesting Code Fragments and won't be discussed in this section.

The next interesting code fragment occurs in the class named MyListActionListener which is designed to respond whenever the user double-clicks on a selected item in the List object. If the user double-clicks on a single selection in the List object, the overridden actionPerformed() method identifies and displays the selected item by using the getSelectedItem() method of the List class. However, if the user double-clicks when more than one item is selected, the getSelectedItem() method returns null and the event is effectively ignored by this ActionListener object.
public void actionPerformed(ActionEvent e){

  if(aList.getSelectedItem() != null){

    System.out.println("Single Item Selection");

      System.out.println("  " + aList.getSelectedItem());

  }//end-if

}//end actionPerformed()
The next interesting code fragment occurs in an ActionListener class designed to respond to a click on a Button object and display the one or more items selected in the List object. In this case, the getSelectedItems() method (note the plural "Items" in the name of this method) of the List class is used to create a String array containing all of the items that were selected when the user clicked the Button object. Typical array processing is performed in the overridden actionPerformed() method to either display all the strings in the array, or to display nothing if the array is empty. This latter case occurs if the user clicks the Button object when no items are selected.
public void actionPerformed(ActionEvent e){

  String[] tempString = aList.getSelectedItems();

  if(tempString.length != 0){

    System.out.println("Multiple Item Selection");      

    for(int cnt = 0; cnt < tempString.length; cnt++)

      System.out.println("  " + tempString[cnt]);

  }//end-if

}//end actionPerformed()
See the next section for a complete listing of the program.

Program Listing of List Class Program

This section contains a complete listing of the program along with additional comments. See the previous sections for an operational description of the program.
/*File List01.java Copyright 1997, R.G.Baldwin



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 List01 {

  public static void main(String[] args){

    GUI gui = new GUI();

  }//end main

}//end class List01

//=======================================================//



class GUI {

  public GUI(){//constructor



    //Instantiate a List object and place some String 

    // objects in it.

    List myList = new List();

    for(int cnt = 0; cnt < 15; cnt++) 

      myList.add("List Item " + cnt);



    myList.setMultipleMode(true);//allow multiple selection

    myList.select(1);//display item[1] on startup



    //Instantiate and register an ActionListener object on

    // the List object. Action event occurs when the user 

    // double-clicks on an item.

    myList.addActionListener(

                         new MyListActionListener(myList));



    //Instantiate a Button object to service multiple-item

    // selections. Also instantiate and register an 

    // ActionListener object on the Button.    

    Button myButton = new Button("Select Multiple Items");

    myButton.addActionListener(

                       new MyButtonActionListener(myList));

    

    //Place the List object and the Button object in 

    // a Frame object.

    Frame myFrame = new Frame(

                           "Copyright 1997, R.G.Baldwin");

    myFrame.setLayout(new FlowLayout());    

    myFrame.add(myList);

    myFrame.add(myButton);

    myFrame.setSize(250,150);

    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 listen for ActionListener events on the List

  // object  Displays the item selected when the user 

  // double-clicks an item in the list when only one item

  // is selected.  If the user double-clicks on a multiple

  // selection, an event occurs but the getSelectedItem()

  // method of the List class returns null and nothing is

  // displayed.

  class MyListActionListener implements ActionListener{

    List aList;

    

    MyListActionListener(List inList){//constructor

      aList = inList;//save a reference to the List object

    }//end constructor

    

    //Override the actionPerformed() method of the 

    // ActionListener interface.

    public void actionPerformed(ActionEvent e){

      if(aList.getSelectedItem() != null){

        System.out.println("Single Item Selection");

        System.out.println("  " + aList.getSelectedItem());

      }//end-if

    }//end actionPerformed()

  }//end class MyListActionListener

//=======================================================//



//Class to listen for ActionListener events on the Button

// object. Displays the items selected when the user 

// clicks the Button object, even if only one item is 

// selected. If no items are selected, nothing is 

// displayed.

class MyButtonActionListener implements ActionListener{

  List aList;

    

  MyButtonActionListener(List inList){//constructor

    aList = inList;//save a reference to the List object

  }//end constructor

    

  //Override the actionPerformed() method of the 

  // ActionListener interface.

  public void actionPerformed(ActionEvent e){

    String[] tempString = aList.getSelectedItems();

    if(tempString.length != 0){

      System.out.println("Multiple Item Selection");      

      for(int cnt = 0; cnt < tempString.length; cnt++)

        System.out.println("  " + tempString[cnt]);

    }//end-if

  }//end actionPerformed()

}//end class MyListActionListener

//=======================================================//



class Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate
.

Review

Q - Write a Java program that meets the following specifications.
/*File SampProg148.java Copyright 1997, R.G.Baldwin

From lesson 132



Without viewing the solution, write a Java program that

meets the following specifications.



When this program starts, a Frame appears with your name

in the banner at the top.  There are four Checkbox objects

in the Frame, labeled A, B, C, and D.  Only one of them

can be selected at any time.  The Checkbox object labeled

B cannot be selected.  An attempt to select it causes

the Checkbox object labeled A to be selected instead.



When you click on the close button on the Frame, the 

program terminates and returns control to the operating

system.



The program was tested using JDK 1.1.3 running under Win95.

**********************************************************/



import java.awt.*;

import java.awt.event.*;

import java.util.*;

//=======================================================//

public class SampProg148 {

  public static void main(String[] args){

    //instantiate a Graphical User Interface object

    GUI gui = new GUI();

  }//end main

}//end class SampProg148

//=======================================================//



class GUI {

  Checkbox checkboxA;

  public GUI(){//constructor



    //Create CheckboxGroup object

    CheckboxGroup checkBoxGroup1 = new CheckboxGroup();

    

    //Create Checkbox objects and assign to group

    checkboxA = new Checkbox("A",true, checkBoxGroup1);

    Checkbox checkboxB = new Checkbox(

                               "B",false,checkBoxGroup1);

    Checkbox checkboxC = new Checkbox(

                               "C",false,checkBoxGroup1);

    Checkbox checkboxD = new Checkbox(

                               "D",false,checkBoxGroup1);



    //This is an inner class for an ItemListener

    class myItemListener implements ItemListener{

      public void itemStateChanged(ItemEvent e){

        //When an attempt is made to select checkboxB

        // set the state of checkboxA to true.

        if(e.getStateChange() == ItemEvent.SELECTED)

          checkboxA.setState(true);

      }//end itemStateChanged

    }//end class myItemListener

    

    checkboxB.addItemListener(new myItemListener());

       

    Frame myFrame = new Frame(

                           "Copyright 1997, R.G.Baldwin");

    myFrame.setLayout(new FlowLayout());    

    myFrame.add(checkboxA);

    myFrame.add(checkboxB);

    myFrame.add(checkboxC);

    myFrame.add(checkboxD);

    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 Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate
Q - Write a Java program that meets the following specifications.
/*File SampProg149.java Copyright 1997, R.G.Baldwin

From lesson 132.



Without viewing the solution that follows, write a Java

program that meets the following specifications.



When the program starts running, a Frame appears on the

screen with your name in the banner at the top.



The Frame contains two Choice objects.  Each Choice object

contains three items.  There are no duplicate items.



When you make a selection in one Choice object, the

selected item disappears from that Choice object and 

reappears in the other Choice object.



When you click the close button on the Frame, the program

terminates, returning control to the operating system.



The program was tested using JDK 1.1.3 running under Win95.

**********************************************************/



import java.awt.*;

import java.awt.event.*;

import java.util.*;

//=======================================================//

public class SampProg149 {

  public static void main(String[] args){

    //instantiate a Graphical User Interface object

    GUI gui = new GUI();

  }//end main

}//end class SampProg149

//=======================================================//



class GUI {

  Choice myChoice1; //refs to two Choice objects

  Choice myChoice2;

  

  public GUI(){//constructor



    //Instantiate a Choice object and place some String 

    // objects in it.

    myChoice1 = new Choice();

    myChoice1.add("123");

    myChoice1.add("456");

    myChoice1.add("789");

    

    myChoice2 = new Choice();

    myChoice2.add("ABC");

    myChoice2.add("DEF");

    myChoice2.add("GHI");



    //These are inner classes

    class MyItemListener1 implements ItemListener{

      public void itemStateChanged(ItemEvent e){

        String temp = myChoice1.getSelectedItem();

        myChoice1.remove(temp);

        myChoice2.add(temp);

      }//end itemStateChanged()

    }//end class MyItemListener1    

       

    class MyItemListener2 implements ItemListener{

      public void itemStateChanged(ItemEvent e){

        String temp = myChoice2.getSelectedItem();

        myChoice2.remove(temp);

        myChoice1.add(temp);

      }//end itemStateChanged()

    }//end class MyItemListener2 



    myChoice1.addItemListener(new MyItemListener1());

    myChoice2.addItemListener(new MyItemListener2());

    

    Frame myFrame = new Frame(

                            "Copyright 1997, R.G.Baldwin");

    myFrame.setLayout(new FlowLayout());    

    myFrame.add(myChoice1);

    myFrame.add(myChoice2);

    myFrame.setSize(250,150);

    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 Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate
Q - Write a Java program that meets the following specifications.
/*File SampProg150.java Copyright 1997, R.G.Baldwin

From lesson 132



Without viewing the following solution, write a Java

program that meets the following specifications.



The program starts with a Frame object containing a

List object displayed on the screen. The size of the

Frame is 250x150.  The List object completely fills the

client area of the Frame object.



The List object contains about 15 items.  Only one item

can be highlighted at any one time.



Whenever you cause an item to be highlighted, that

item is displayed on the screen.



When you click the close box on the Frame, the program

terminates and control returns to the operating system.



The program was tested using JDK 1.1.3 running under Win95.

**********************************************************/



import java.awt.*;

import java.awt.event.*;

//=======================================================//

public class SampProg150 {

  public static void main(String[] args){

    GUI gui = new GUI();

  }//end main

}//end class SampProg150

//=======================================================//



class GUI {

  List myList;//ref to List object

  

  public GUI(){//constructor



    //Instantiate a List object and place some String 

    // objects in it.

    myList = new List();

    for(int cnt = 0; cnt < 15; cnt++) 

      myList.add("List Item " + cnt);



    //This is an inner class

    class MyListItemListener implements ItemListener{

        public void itemStateChanged(ItemEvent e){

          System.out.println(myList.getSelectedItem());

      }//end itemStateChanged()

    }//end class MyListItemListener



    //Instantiate and register an ItemListener object on

    // the List object. 

    myList.addItemListener(new MyListItemListener());



    //Place the List object in a Frame object.

    Frame myFrame = new Frame(

                           "Copyright 1997, R.G.Baldwin");

    myFrame.add(myList);

    myFrame.setSize(250,150);

    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 Terminate extends WindowAdapter{

  public void windowClosing(WindowEvent e){

    System.exit(0);//terminate the program

  }//end windowClosing

}//end class Terminate
-end-


These tutorials were developed by Richard Baldwin and are the copyrighted property of Richard Baldwin. You have permission to print one copy for your own use, but may not, without written permission from Richard Baldwin, redistribute the tutorial documents.

The base material in these lessons is believed by the author to be in the public domain. If you use these lessons for any purpose, you are using them at your own risk, and this author assumes no responsibility or liability for any damages that you may incur.

Java, Sun, HotJava and various other related symbols and names are registered trademarks of Sun Microsystems, Inc. Macintosh is a registered trademark of Apple Computer, Inc. OS/2 is a registered trademark of International Business Machines Corporation. Microsoft, MS-DOS, Visual Basic, Windows, Windows NT, Internet Explorer and Visual J++ are registered trademarks of Microsoft Corporation. Netscape and JavaScript are trademarks of Netscape Communications Corporation. All other trademarks and service marks that may have been inadvertently used in these lessons without proper credit being given are the property of their respective owners. If you feel that your trademark or copyright has been compromised, please notify this author immediately, and an appropriate correction to the document will be issued.


© 1996, 1997, 1998, 1999 Richard G. Baldwin