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.
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:
This lesson will concentrate on the Non-Text Input classes.
The first four of the following five classes extend the class Component.
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." |
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.
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.
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.
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." |
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." |
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.
checkbox1 B
checkbox2 C
checkbox3 D
The program was tested using JDK 1.1 running under Win95.
CheckboxGroup myCheckboxGroup = new CheckboxGroup(); |
Button myButton = new Button("OK"); myButton.addActionListener( new MyActionListener(myCheckboxGroup)); |
myFrame.add(new Checkbox("A",true, myCheckboxGroup)); |
public void actionPerformed(ActionEvent e){ System.out.println( aCheckBoxGroup.getSelectedCheckbox().getName()+ " " + aCheckBoxGroup.getSelectedCheckbox().getLabel()); }//end actionPerformed() |
/*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 //=======================================================// |
"The Choice class is a pop-up menu of choices. The current choice is displayed as the title of the menu." |
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. |
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 program places a Choice object in a Frame object. Three String objects are added to the Choice object:
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.
Choice myChoice = new Choice(); myChoice.add("First Choice"); ... |
myChoice.select("Second Choice"); |
myChoice.addItemListener(new MyItemListener(myChoice)); |
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() |
/*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 List class is described in the documentation as:
"A scrolling list of text items." |
As of 3/12/97, the List class has no fields and has the following three public constructors:
The following is a partial list of methods in the class.
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 3A 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.
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 |
myList.addActionListener(new MyListActionListener(myList)); |
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() |
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() |
/*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 |
/*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 |
/*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 |
/*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 |
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