Chapter 11 - The java.awt Package: Components and Facilities
Chapter 11: The java.awt Package: Components and 
Facilities 
Objectives 
This chapter helps you to prepare for the exam by covering the following objectives: 
Know what the AWT is and how it is used. 
. 
A general knowledge of what the AWT is and how it is used is required for the certification 
exam. 
Know what components and containers are supported by the AWT and how they are used.
. 
Although you don't need to know all the details about the AWT's components and 
containers, the exam assumes that you know the basics about how each component and 
container is used. You will be required to know the components by name and have a basic 
familiarity with their constructors, properties, and methods. 
Know how to use components and containers to build GUI-based applications and applets.
. 
To build a basic GUI application or applet, you need to assemble the AWT's component and 
container pieces into a final program. You need to have some hands-on experience using 
the AWT components and containers to correctly answer these exam questions. 
Note 
Layouts and Event Handlers This chapter uses layouts and event handlers to 
build simple GUI applications and applets. However, these topics are covered in 
more detail in subsequent chapters. 
Study Strategies 
As you read through this chapter, you should concentrate on the following key items: 
. 
How the AWT is used to build graphical user interfaces. 
. 
What components and containers are supported by the AWT. 
. 
How each component and container is used. 
. 
How components and containers are assembled into applets and applications. 
Chapter Introduction 
This chapter covers the GUI components and containers of java.awt. You'll work with labels, buttons, 
text fields, check boxes, choices, lists, and scrollbars. You'll also learn how to use components and 
containers. Familiarity with these AWT classes and interfaces is essential to developing a Java-based 
GUI, and you can expect to see several exam questions that require knowledge of them. By studying 
the component and container descriptions in this chapter and working the programming examples, you 
should be able to do well on related exam questions. Subsequent chapters will expand on the material 
introduced in this chapters. 
- 177 
Components and Containers 
The AWT supports the development of graphical user interfaces through the use of components and 
containers. Components refer to visible user interface elements, such as labels, buttons, text fields, and 
scrollbars. Containers are components that contain and organize other components. Examples of 
containers are windows, dialog boxes, and applets. In general, components extend the Componentclass and containers extend the 
Container class. Since containers are also components, the 
Container class is a subclass of the Component class. Some components extend the 
MenuComponent class, which is not a subclass of Component, but a separate component class 
hierarchy that is devoted to menu-related components. Figure 11.1 provides an overview of how the 
AWT's components and containers are organized into a class hierarchy. 
Figure 11.1: The AWT component and container class hierarchy. 
We'll start with the Container class and describe the non-container components that it supports. Then 
we'll cover the Component class and describe its subclasses. Finally, we'll wrap up with 
MenuComponent and the menu-related classes of java.awt. 
AWT Components 
The Component class is the superclass of the set of AWT classes that implement graphical user 
interface controls. These components include windows, dialog boxes, buttons, labels, text fields, and 
other common GUI components. The Component class provides a common set of methods that are 
used by all these subclasses, including methods for working with event handlers, images, fonts, and 
colors. More than 100 methods are implemented by this class. It is a good idea to browse the API pages 
of the Component class to get a feel for the kinds of methods that are available because they are 
inherited by all the subclasses of Component. While the certification exam will not test you on all these 
methods, there are a few that you should be familiar with: 
. 
getBounds() and setBounds()—Gets and sets the size and position of a component. 
These parameters are usually determined by a layout manager, as described in Chapter 12, 
"The java.awt Package: Layout." 
. 
getBackground(), setBackground(), getForeground(), and setForeground()— 
Gets and sets the component's background and foreground colors. By default, these colors 
are inherited from the component's parent container. 
. 
getEnabled() and setEnabled()—Causes a component to be enabled or disabled. A 
disabled component is displayed in a way that indicates that it is nonoperational (usually 
grayed-out). 
. 
getFont() and setFont()—Gets and sets the font used with the component. By default, 
the font is inherited from the component's container. 
. 
getParent()—Returns the component's container (if any). 
. 
getSize(), setSize(), getPreferredSize(), and setPreferredSize()—Gets 
and sets the actual and preferred (minimum required) size of a component. The size set by 
these methods may be (and usually is) overridden by layout managers. 
- 178 
. 
setVisible()—Causes a component to be displayed or hidden. 
The above methods are important in that they are typically used when working with any Componentand Container subclasses. 
The subclasses of Component define the major components of the AWT. They are summarized here 
and covered in the following subsections: 
. 
Button—A push button 
. 
Canvas—A canvas used for drawing and painting 
. 
Checkbox—A check box or radio button 
. 
Choice—A pulldown list of choices. 
. 
Container—Superclass of containers, such as windows, dialog boxes, and applets. 
. 
Label—A text label 
. 
List—A list from which one or more selections may be made 
. 
Scrollbar—A scrollbar 
. 
TextComponent—Superclass of single- and multiple-line text fields 
The Box.Filler class also extends Component. However, it is not part of the java.awt package 
and does nothing other than to take up space when components of a container are laid out. 
Labels 
The most basic GUI component is the label, which is simply text that is displayed at a particular location 
of a GUI container. The Label class of the java.awt package provides the capability to work with 
labels. This class provides three Label() constructors: a default parameterless constructor for creating 
blank Label objects, a constructor that takes a String object that specifies the label's text, and a 
constructor that takes a String object (the label's text) and an alignment constant. The alignment 
constant may be LEFT, CENTER, or RIGHT. 
The alignment constants determine the justification of text within the label. The Label class provides 
methods for working with the label's text and alignment, and for performing other operations. The 
setText() and getText() methods are used to access the label's text. 
Buttons 
Buttons are another fundamental GUI component. Unlike labels, which are used solely to provide 
information to the user, buttons enable users to interact with applets and applications. 
The Button class of java.awt provides the capability to create labeled buttons. The Button class 
has two constructors: a default parameterless constructor that creates unlabeled buttons and a 
constructor that takes a String object (the button's label) as a parameter. The Button class provides 
methods for getting and setting the button's label—getLabel() and setLabel()—and for handling 
button-related events. 
Figure 11.2: The window displayed by ButtonApp. 
The ButtonApp (Listing 11.1) program illustrates the use of the Button and Label classes. Figure 
11.2 shows the default window that it displays. Click on any of the buttons and the text label is updated 
with the button's label. 
Listing 11.1: The Buttonapp Program 
import java.awt.*; 
import java.awt.event.*; 
public class ButtonApp extends Frame { 
- 179 
Label label = new Label("Default Label")
; 
Button button1 = new Button("One")
; 
Button button2 = new Button("Two")
; 
Button button3 = new Button("Three")
; 
Panel panel1 = new Panel()
; 
Panel panel2 = new Panel()
; 
public static void main(String[] args) 
{ 
 ButtonApp app = new ButtonApp()
; 
} 
public ButtonApp() 
{ 
 super("ButtonApp")
; 
panel1.add(label)
; 
button1.addActionListener(new ButtonHandler())
; 
button2.addActionListener(new ButtonHandler())
; 
button3.addActionListener(new ButtonHandler())
; 
panel2.add(button1)
; 
panel2.add(button2)
; 
panel2.add(button3)
; 
add("North",panel1)
; 
add("Center",panel2)
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
show()
; 
} 
class ButtonHandler implements ActionListener 
{ 
 public void actionPerformed(ActionEvent e)
{ 
String s = e.getActionCommand()
; 
label.setText(s)
; 
} 
} 
class WindowEventHandler extends WindowAdapter{ 
- 180 
public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
Text Components
The TextComponent class is the superclass of all text-based classes. It provides a common set of 
methods used by its TextField and TextArea subclasses. It does not provide any constructors and 
cannot be instantiated. It provides methods for getting and setting the text that is displayed in a text 
object—getText() and setText()—setting the text object to an editable or read-only state— 
setEditable()—handling text-editing events, and selecting text that is contained within an object. 
TextField 
The TextField class implements a one-line text entry field. It provides four constructors that are used 
to specify the width of the text field in character columns and the default text to be displayed within the 
field. It provides several methods for accessing the field's size and for specifying whether the characters 
typed by the user should be displayed. The setEchoCharacter() method is used to specify a 
character that is to be displayed in lieu of text typed by the user. This method is used to implement 
password-like fields, fields that display a string of asterisks instead of the characters that the user is 
typing.
TextArea 
The TextArea class implements scrollable text entry objects that span multiple lines and columns. It 
provides five constructors that enable you to specify the number of rows and columns and the default 
text display. It provides several methods that return the dimensions of the text area and then insert, 
append, and replace the text that is contained in that text area. It also provides the capability to set the 
text to read-only or edit mode. 
Figure 11.3: The TextApp default window. 
The TextApp program (Listing 11.2) illustrates the use of the TextField and TextArea classes. See 
the program running in Figure 11.3. Enter text into the text field and click the Append button. The text is 
appended to the text area. Click the Clear button and the text area is cleared. 
TextappListing 11.2: The Program 
import java.awt.*; 
- 181 
import java.awt.event.*; 
public class TextApp extends Frame { 
TextField textField = new TextField(40); 
TextArea textArea = new TextArea(5,40); 
Button append = new Button("Append"); 
Button clear = new Button("Clear"); 
public static void main(String[] args) { 
 TextApp app = new TextApp()
; 
} 
public TextApp() 
{ 
 super("TextApp")
; 
Panel panel1 = new Panel()
; 
Panel panel2 = new Panel()
; 
append.addActionListener(new ButtonHandler())
; 
clear.addActionListener(new ButtonHandler())
; 
panel1.add(append)
; 
panel1.add(clear)
; 
panel2.add(textField)
; 
panel2.add(textArea)
; 
add("North",panel1)
; 
add("Center",panel2)
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
setSize(350,250)
; 
show()
; 
} 
class ButtonHandler implements ActionListener 
{ 
 public void actionPerformed(ActionEvent ev)
{ 
String s=ev.getActionCommand()
; 
if(s.equals("Append")) 
{ 
- 182 
String text = textArea.getText(); 
if(!text.equals("")) text += "\n"+textField.getText(); 
else text = textField.getText(); 
textArea.setText(text); 
 }else if(s.equals("Clear")) textArea.setText(""); 
} 
} 
class WindowEventHandler extends WindowAdapter{ 
 public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
Check Boxes 
The Checkbox class is used to implement labeled check box and radio button GUI controls. If a 
Checkbox object is not associated with a CheckboxGroup object, it is implemented as a traditional 
check box. If a Checkbox object is associated with a CheckboxGroup object, it is implemented as a 
radio button. 
The Checkbox class provides five constructors that enable you to specify the check box label, initial 
state, and CheckboxGroup object. The Checkbox class provides methods for getting and setting the 
label—getLabel() and setLabel()—and state of the check box—getState() and 
setState()—and its CheckboxGroup object, if any. The state of the check box is boolean. The 
Checkbox class also provides methods for identifying event handling code. 
The CheckboxGroup class is used with the Checkbox class to implement radio buttons. All Checkbox 
objects that are associated with a CheckboxGroup object are treated as a single set of radio buttons. 
Only one button in the group may be set to On at a given point in time. The setState() method of a 
Checkbox object can be used to set the state of a radio button to "on." It also resets the state of all 
other radio buttons in the CheckboxGroup to the "off" state. The CheckboxGroup provides a single, 
parameterless constructor. It also provides methods for getting and setting the Checkbox object. 
The CheckboxApp program (Listing 11.3) shows how Checkbox objects can be used as both check 
boxes and radio buttons. Figure 11.4 shows the default window displayed by CheckboxApp. Click any 
of the radio buttons or check boxes, and the text area displays the results of your click. 
Figure 11.4: The window displayed by CheckboxApp
Listing 11.3: The Checkboxapp Program 
- 183 
import java.awt.*; 
import java.awt.event.*; 
public class CheckboxApp extends Frame { 
TextArea textArea = new TextArea(5,10); 
public static void main(String[] args) { 
 CheckboxApp app = new CheckboxApp()
; 
} 
public CheckboxApp() 
{ 
 super("CheckboxApp")
; 
Panel panel1 = new Panel()
; 
Panel panel2 = new Panel()
; 
Checkbox one = new Checkbox("One")
; 
Checkbox two = new Checkbox("Two")
; 
Checkbox three = new Checkbox("Three")
; 
CheckboxGroup group = new CheckboxGroup()
; 
one.setCheckboxGroup(group)
; 
two.setCheckboxGroup(group)
; 
three.setCheckboxGroup(group)
; 
one.setState(true)
; 
Checkbox a = new Checkbox("A")
; 
Checkbox b = new Checkbox("B")
; 
Checkbox c = new Checkbox("C")
; 
CheckboxHandler ch = new CheckboxHandler()
; 
one.addItemListener(ch)
; 
two.addItemListener(ch)
; 
three.addItemListener(ch)
; 
a.addItemListener(ch)
; 
b.addItemListener(ch)
; 
c.addItemListener(ch)
; 
- 184 
panel1.add(one)
; 
panel1.add(two)
; 
panel1.add(three)
; 
panel2.add(a)
; 
panel2.add(b)
; 
panel2.add(c)
; 
add(panel1,"West")
; 
add(panel2,"East")
; 
add(textArea,"South")
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
setSize(400,200)
; 
show()
; 
} 
class CheckboxHandler implements ItemListener 
{ 
 public void itemStateChanged(ItemEvent e)
{ 
String status; 
Checkbox checkbox = (Checkbox) e.getItemSelectable()
; 
if(checkbox.getState()) status = "You checked: "
; 
else status = "You unchecked: "
; 
status += checkbox.getLabel()
; 
textArea.setText(status)
;
 
} 
} 
class WindowEventHandler extends WindowAdapter{ 
 public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
- 185 
Choices and Lists 
The Choice class is used to implement pull-down lists that can be placed in the main area of a window. 
These lists are known as option menus. These are pop-up menus that enable the user to select a single 
menu value. The Choice class provides a single, parameterless constructor. It also provides access 
methods that are used to add items to the list, count the number of items contained in the list, select a 
list item, handle events, and determine which list item is selected. 
The List class implements single- and multiple-selection list GUI controls. The lists provided by the 
List class are more sophisticated than those provided by the Choice class. The List class lets you 
specify the size of the scrollable window in which the list items are displayed and select multiple items 
from the list. The List class has the following three constructors: 
. 
List()
. 
List(int rows)
. 
List(int rows, boolean multipleMode)
The first one takes no parameters and constructs a generic List object. The second one allows you to 
select the number of rows in the visible window. The third one enables you to specify the number of 
rows and also whether or not multiple selections are allowed. 
The List class provides several access methods that are used to add, delete, and replace list items, 
count the number of items in the list, determine which items are selected, handle events, and select 
items within the list. I recommend that you browse the API description of the List class to get an idea of 
the methods that it supports. 
Figure 11.5: The ChooserApp window. 
The ChooserApp program (Listing 11.4) shows how Choice and List objects are used in a GUI. 
Figure 11.5 shows the ChooserApp program running. Use the Choice object on the left of the screen 
to select a meal. Use the menu item List object on the right of the screen to select one or more items 
to order for that meal. The results of your order are displayed in the TextField object. 
Listing 11.4: The Chooserapp Program 
import java.awt.*; 
import java.awt.event.*; 
public class ChooserApp extends Frame { 
MyChoice mealChoice; 
MyList currentList; 
MyList mealList[]; 
String meals[] = {"Breakfast","Lunch","Dinner"}; 
- 186 
String mealChoices[][] = { 
{"pancakes","eggs","bacon","ham","sausage","cereal", 
"toast","coffee","juice"}, 
{"pizza","hamburger","hot dog","burrito","salad","fries", 
"chips","soda","milk"}, 
{"spaghetti","carne asada","barbequed chicken","soup","salad", 
 "bread","wine","beer","soda","milk"
} 
}
; 
TextField text; 
public static void main(String[] args) 
{ 
 ChooserApp app = new ChooserApp()
; 
} 
public ChooserApp() 
{ 
 super("ChooserApp")
; 
setupChoice()
; 
setupLists()
; 
text = new TextField(40)
; 
add("North",new Label("Place your order:"))
; 
add("South",text)
; 
add("West",mealChoice)
; 
currentList = mealList[0]
; 
add("East",currentList)
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
setSize(300,200)
; 
show()
; 
} 
 void setupChoice()
{ 
mealChoice = new MyChoice(meals)
; 
mealChoice.addItemListener(new ChoiceHandler())
;
 
} 
- 187 
void setupLists(){ 
mealList = new MyList[meals.length]; 
ListHandler lh = new ListHandler(); 
for(int i=0;i
 mealList[i] = new MyList(5,true,mealChoices[i])
; 
mealList[i].addItemListener(lh)
; 
} 
} 
class ChoiceHandler implements ItemListener { 
 public void itemStateChanged(ItemEvent e){ 
for(int i=0;i
 if(meals[i].equals(mealChoice.getSelectedItem())){ 
remove(currentList); 
currentList = mealList[i]; 
add("East",currentList); 
text.setText(meals[i]); 
} 
validate()
; 
} 
} 
class ListHandler implements ItemListener { 
 public void itemStateChanged(ItemEvent e){ 
String order = mealChoice.getSelectedItem()+": "; 
String items[] = currentList.getSelectedItems(); 
for(int i=0;i
} 
} 
class WindowEventHandler extends WindowAdapter{ 
 public void windowClosing(WindowEvent e) { 
System.exit(0); 
- 188 
} 
} 
} 
class MyList extends List {
 public MyList(int rows,boolean multiple,String labels[]) { 
super(rows,multiple); 
int length = labels.length; 
for(int i=0;i
try 
{ 
add(labels[i])
; 
}catch (NullPointerException ex) 
{ 
add("")
; 
} 
} 
} 
} 
class MyChoice extends Choice { 
 public MyChoice(String labels[]) { 
super(); 
int length = labels.length; 
for(int i=0;i
try 
{ 
add(labels[i])
; 
}catch (NullPointerException ex) 
{ 
add("")
; 
} 
} 
}} 
- 189 
Scrollbars 
The Scrollbar class is used to implement vertical and horizontal scrollbars. It provides three 
constructors that enable you to specify the orientation of the scrollbar and the parameters that control 
the scrollbar's operation. It provides several methods that allow the scrollbar's parameters and current 
value to be read and set. 
When you use scrollbars in your Java programs, you will probably use them to scroll through a 
Graphics object that is associated with a Canvas object or the main application window. (These 
objects are covered in the following chapter.) You create and place scrollbars in your window in the 
same manner as any other window component. Their position and size within the window are 
determined by the layout associated with the window. 
Scrollbars are created using the Scrollbar()constructor. Three forms of this constructor are 
provided. The default constructor takes no parameters and is not particularly useful, unless you want to 
create a Scrollbar object and then specify its orientation and use later in your program. The second 
constructor allows the orientation of a Scrollbar object to be specified. The third Scrollbar() 
constructor uses the five parameters that are needed to create a working scrollbar: orientation, 
value, visible, minimum, and maximum. 
The orientation of a scrollbar is specified by the VERTICAL and HORIZONTAL constants defined by 
the Scrollbar class. The minimum and maximum parameters specify the range of the scrollbar. 
These values should map to the object being scrolled. For example, if you are scrolling a 1,000-line text 
object, appropriate minimum and maximum values for a vertical scrollbar would be 0and 999. 
Horizontal values can be determined using the maximum width of the text to be scrolled (in pixels). 
The value parameter identifies the starting value associated with the scrollbar. The value parameter 
is usually set to the minimum value of the scrollbar. However, suppose you wanted to initiate the 
display of an object with its center displayed on the screen. You would then set the scrollbar's value 
parameter to the average of its minimum and maximum values. 
The visible parameter is used to specify the size of the viewable area of the object being scrolled. 
For example, if you are scrolling a 1,000-line text object and the viewable area of the window is 25 lines 
long, you would set the visible variable to 25. The visible parameter also determines the actual 
maximum value of the scrollbar. In this example, the maximum value would be 1000 - 25 = 975. 
The Scrollbar class provides several methods for getting and setting the parameters of a 
Scrollbar object. The getOrientation(), getValue(), getVisibleAmount(), 
getMinimum(), and getMaximum() methods retrieve the parameter values discussed so far. The 
getValue() method is used to determine the position to which the user has scrolled. 
The setUnitIncrement() and setBlockIncrement() methods are used to specify the size of a 
scrollable unit and page relative to the minimum and maximum values associated with a scrollbar. For 
example, when scrolling text, you can set the unit increment of a vertical scrollbar to one so that only 
one line of text is vertically scrolled. You can set the page increment to 10 to allow 10 lines of text to be 
scrolled when the user clicks between the tab and arrows of a scrollbar. The getUnitIncrement() 
and getBlockIncrement() methods provide access to the current unit- and page-increment values. 
The block increment is equal or slightly less than the visible amount. 
The setValue() method enables you to directly set the current position of a scrollbar. The 
setValues() method allows you to specify a scrollbar's value, visible, minimum, and maximum 
parameters. 
The ScrollerApp program (Listing 11.5) shows how scrollbars are used. Figure 11.6 shows the 
ScrollerApp program running. Move the vertical or horizontal scrollbar and the text label is updated to 
display the scrollbar's new position. 
Figure 11.6: The ScrollerApp window. 
- 190 
Listing 11.5: The Scrollerapp Program 
import java.awt.*; 
import java.awt.event.*; 
public class ScrollerApp extends Frame { 
Label label = new Label("Scrollbar Position"); 
MyScrollbar hscroll = new MyScrollbar(Scrollbar.HORIZONTAL, 
50,1,0,100,label); 
MyScrollbar vscroll = new MyScrollbar(Scrollbar.VERTICAL, 
500,10,0,1000,label); 
public static void main(String[] args) { 
 ScrollerApp app = new ScrollerApp(); 
} 
public ScrollerApp() { 
 super("ScrollerApp")
; 
add("Center",label)
; 
add("West",vscroll)
; 
add("North",hscroll)
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
setSize(200,200)
; 
show()
; 
} 
class WindowEventHandler extends WindowAdapter{ 
public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
class MyScrollbar extends Scrollbar { 
- 191 
Label position; 
 String direction = " Horizontal"; 
 public MyScrollbar(int orientation,int value,int visible,int min,int max, 
Label label) { 
super(orientation,value,visible,min,max); 
position=label; 
if(orientation==Scrollbar.VERTICAL) direction = " Vertical"; 
addAdjustmentListener(new MyScrollbar.HandleScrolling()); 
} 
 class HandleScrolling implements AdjustmentListener { 
public void adjustmentValueChanged(AdjustmentEvent e){ 
position.setText(direction+" Position: "+e.getValue()); 
} 
} 
} 
Canvas 
The Canvas class provides an area of the screen that is used for drawing and painting. You generally 
extend the Canvas class and override its paint() method to accomplish custom drawing and painting. 
Each Canvas object is associated with a Graphics object that is used to perform the actual drawing 
and painting. Chapter 14, "The java.awt.Package: Painting," covers the Canvas class in more 
detail. 
AWT Containers 
Although Component contains many GUI-related subclasses, its Container subclass is used to define 
components that can contain other components. It provides methods for adding, retrieving, displaying, 
counting, and removing the components that it contains. The Container class also provides methods 
for working with layouts, which are used to control the layout of components within a container. Methods 
that you should become familiar with are: 
. 
add()—Used to add a component to the container (usually under the control of a layout 
class). 
. 
getComponent() and getComponentAt()—Obtains a reference to a component in the 
container. 
. 
getInsets()—Returns information about a container's border. 
. 
remove() and removeAll()—Removes components from the container. 
. 
getLayout() and setLayout()—Gets and sets the way in which the components of the 
container are organized. 
. 
validate() and validateTree()—Causes the container to be laid out and redisplayed. 
The Container class has three major AWT subclasses: Window, Panel, and ScrollPane. Window 
provides a common superclass for application main windows (Frame objects) and Dialog windows. 
The Panel class is a generic container that can be displayed within an applet or window. It is 
subclassed by the java.applet.Applet class as the base class for all Java applets. The 
ScrollPane class is a scrollable container that can have vertical and horizontal scrollbars. 
- 192 
Window 
The Window class provides an encapsulation of a generic Window object. It is subclassed by Frame 
and Dialog to provide the capabilities needed to support application main windows and dialog box 
support. 
The Window class provides two constructors that create Window objects with a Frame or a Window as 
the parent. The parent must be specified because only objects of the Frame class or its subclasses 
contain the functionality needed to implement a main application window. 
Note Swing Containers The Container class also has several Swing subclasses. 
However, because Swing is not part of the certification exam (and a large topic of 
its own) I do not cover the Swing subclasses. 
The Window class provides important methods that are used by its Frame and Dialog subclasses. 
The pack() method is used to size the components of a window according to their preferred size and 
arrange them according to the window layout style. The pack() method should be invoked before a 
window is displayed. The setSize() method sets the vertical and horizontal dimensions of the 
window. The show() method is used to display a window. Windows are hidden (invisible) by default, 
and are only displayed as a result of invoking their show() method. The toFront() and 
toBack()methods are used to position windows relative to their frame window and all other windows 
of the same program. The dispose()method releases the resources associated with a window and 
deletes the Window object. The getWarningString() method is used to retrieve the warning 
message associated with untrusted windows. Warning messages are associated with windows that are 
created by applets. 
A Window object does not have a border or a menubar when it is created. In this state, it may be used 
to implement a pop-up window. 
Frame 
The Frame class is used to provide the main window of an application. It is a subclass of Window that 
supports the capabilities to specify a window icon, cursor, menu bar, and title. Because it implements 
the MenuContainer interface, it is capable of working with MenuBar objects. 
The Frame class defines several constants that can specify different types of cursors to be used within 
the frame. As of JDK 1.1, a sep-arate Cursor class is available for working with cursors. 
Frame provides two constructors: a default parameterless constructor that creates an untitled frame 
window and a constructor that accepts a String argument to be used as the frame window's title. The 
second constructor is typically used. 
Frame extends the set of access methods that it inherits from Window by adding methods to get and 
set the window title, icon image, and menu bar. It also provides methods for removing the menu bar and 
specifying whether the window is resizable. 
Dialog
The Dialog class is a subclass of the Window class that is used to implement dialog box windows. A 
dialog box is usually a smaller temporary window that contains a number of GUI controls for interacting 
with the user. Common examples of dialog boxes are the file open or save dialog boxes that are used to 
select files and directories. The Dialog class enables you to construct modal and non-modal dialog 
boxes. Modal dialog boxes must be closed before control returns to the window that launched them. 
Non-modal dialog boxes that do not need to be closed before other program windows can be accessed. 
The Dialog constructors enable you to specify the Frame or Dialog object containing the dialog box., 
as well as the modal flag and the dialog box's title. 
The Dialog class provides only a handful of access methods. These methods get and set the dialog 
box's title, determine whether it is modal, and get and set its resizable properties.
FileDialog 
The FileDialog class is used to construct dialog boxes that support the selection of files for input and 
output operations. It is a subclass of the Dialog class and provides three constructors. These 
constructors take as arguments the Frame window that contains the dialog box, the title to be used at 
the top of the dialog box, and a mode parameter that can be set to the LOAD or SAVE constants defined 
by FileDialog. 
FileDialog provides methods that are used to access the directory and filename of the user-selected 
file and to specify an object that implements the FileNameFilter interface. The FileNameFilter 
interface is defined in the java.io package. It defines the accept() method, which is used to 
determine the filenames that should be included in a file list. 
- 193 
Figure 11.7: The FileDialogApp window. 
Listing 11.6 shows the FileDialogApp program. It displays the window shown in Figure 11.7. Click on 
the Open FileDialog button and a file dialog box is displayed. Select a filename and click Open. The 
directory and name of the file that you selected are displayed. 
FiledialogappListing 11.6: The Program 
import java.awt.*; 
import java.awt.event.*; 
public class FileDialogApp extends Frame { 
Label label1 = new Label(""); 
Label label2 = new Label(""); 
public static void main(String[] args) { 
 FileDialogApp app = new FileDialogApp()
; 
} 
public FileDialogApp() 
{ 
 super("FileDialogApp")
; 
Panel panel = new Panel()
; 
Panel panel1 = new Panel()
; 
Panel panel2 = new Panel()
; 
Panel panel3 = new Panel()
; 
panel.setLayout(new GridLayout(3,1))
; 
Button button = new Button("Open FileDialog")
; 
panel1.add(button)
; 
panel2.add(label1)
; 
panel3.add(label2)
; 
panel.add(panel1)
; 
panel.add(panel2)
; 
panel.add(panel3)
; 
- 194 
add("Center",panel)
; 
button.addActionListener(new ButtonHandler())
; 
addWindowListener(new WindowEventHandler())
; 
pack()
; 
setSize(400,200)
; 
show()
; 
} 
class ButtonHandler implements ActionListener 
{ 
 public void actionPerformed(ActionEvent e)
{ 
FileDialog fd = new FileDialog(FileDialogApp.this)
; 
fd.show()
; 
label1.setText(fd.getDirectory())
; 
label2.setText(fd.getFile())
; 
validate()
; 
} 
} 
class WindowEventHandler extends WindowAdapter{ 
public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
Panel 
The Panel class is a subclass of Container that provides a rectangular area for organizing 
components. Panel objects typically organize a set of components into a group that can then be 
ordered and laid out as if it were a single component. 
Applet
The Applet class is a subclass of Panel that that is designed to be embedded in a Web page. 
Applet objects are automatically constructed by the user agent (usually a browser) when it displays 
the page, and contains several methods to interact with this environment. It contains a single default 
parameterless constructor, which is generally not used. Applets are constructed by the runtime 
environment when they are loaded and do not have to be explicitly constructed. 
The Applet class contains methods that can display images, play audio files, respond to events, and 
obtain information about an applet's execution environment. This environment is referred to as the 
applet's context. 
- 195 
Even though applets are an important part of Java programming, you probably won't see any appletrelated 
questions on the certification exam. However, you'll see several examples of their use in the 
following chapter on layouts. 
ScrollPane 
The ScrollPane class simplifies the development of scrollable applications. The ScrollPane class is 
like a combination of a panel and vertical and horizontal scrollbars. The great thing about it is that it 
performs all the scrollbar event handling and screen redrawing internally. The fact that the ScrollPane 
class handles events is significant. By handling events internally, it enables scrolling-related operations 
to run significantly faster. 
The ScrollPane class extends the Container class and, therefore, can contain other components. It 
is designed to automate scrolling for a single, contained component, such as a Canvas object. It 
provides two constructors—a single parameterless constructor and a constructor that takes an int 
argument. The parameterless constructor creates a ScrollPane object that displays scrollbars only 
when they are needed. The other constructor takes one of the three constants: SCROLLBARS_ALWAYS, 
SCROLLBARS_AS_NEEDED, and SCROLLBARS_NEVER. These constants determine if and when 
scrollbars are displayed by the ScrollPane object. 
The initial size of the ScrollPane object is 1008100 pixels. The setSize() method can be used to 
resize it. The ScrollPane class provides methods for accessing and updating its internal scrollbars, 
but in most cases this is both unnecessary and ill-advised. Other methods are provided to get and set 
the current scrollbar positions. 
Menus 
Java provides a rich set of menu-related classes for creating and interacting with pull-down menus. The 
MenuComponent class is the superclass of all menu-related classes. Since it extends the Object class 
instead of Component, it defines a separate AWT component class hierarchy. It provides several 
methods, the most useful of which are the following: 
. 
getFont() and setFont()—Gets and sets the font associated with the menu component. 
. 
getName() and setName()—Gets and sets the name of the menu component. 
. 
getParent()—Returns the parent container of the menu component. 
The MenuComponent class has two direct superclasses, MenuBar and MenuItem, which provide most 
of the methods for creating and using menus. 
MenuBar 
The MenuBar class defines the menu bar that is displayed at the top of an application window by a 
Frame object. A Frame object can have one and only one MenuBar object, which is set using the 
setMenuBar() method of the Frame class. A MenuBar object is assigned a set of Menu objects, each 
of which is displayed as a separate pull-down menu. Common examples are the File, Edit, and Help 
pull-down menus found in many window applications. Menu objects are added to a MenuBar object 
using the add() method of the MenuBar class. The MenuBar class lets a special menu be designated 
as a Help menu. It is set using the setHelpMenu() method. The getMenu() and getHelpMenu() 
methods are used to retrieve the Menu objects that have been added to a MenuBar. 
MenuItem 
The MenuItem class extends the MenuComponent class and defines the individual items that may be 
added to a Menu object. Some of its important methods are: 
. 
getLabel() and setLabel() Gets and sets the menu item's label. 
. 
getShortcut() and setShortcut() Gets and sets the MenuShortcut object 
associated with the menu item. A MenuShortcut object defines keystrokes that can be 
entered to select a menu item. 
. 
isEnabled() and setEnabled() Allows the enabled status of the menu item to be 
checked and set. 
Since MenuItem is the superclass of the Menu class, it enables Menu objects to be used as MenuItem 
objects. This enables cascading, multilevel menus to be constructed. MenuItem is also the superclass 
of the CheckboxMenuItem class and provides the capability to implement menu items that can be 
checked or unchecked. 
Menu 
The Menu class is a subclass of MenuItem that implements a pull-down menu. For example, an 
application's File menu would be implemented as a Menu object that is added to a MenuBar. A Menu 
object contains one or more MenuItem objects, which can be a normal user-selectable MenuItem 
object, a CheckboxMenuItem object, or another Menu object. Java supports tear-off menus, which are 
- 196 
menus that can be removed from a menu bar. A tear-off menu is constructed in the same manner as 
a 
regular menu—you only need to set the Boolean tear-off value in the Menu() constructor. Tear-off 
menus are not implemented within Windows 95 or NT, but they are implemented in Solaris and other 
UNIX derivatives.
The Menu class provides several methods for working with MenuItem objects, including the add()
, 
insert(), remove(), and removeAll() methods. The getItem() and getItemCount(
)
methods are used to access the MenuItem objects that have been added to a menu. The 
insertSeparator() method inserts a separator line between menu items. 
CheckboxMenuItem 
The CheckboxMenuItem class extends the MenuItem class and supports menu items that can be 
checked on or off. The getState() and setState() methods are used to access the checked state 
of the menu item. 
Figure 11.8: The MenuApp window. 
The MenuApp program shown in Listing 11.7 shows how the MenuBar, Menu, MenuItem, and 
CheckboxMenuItem classes are used. It displays the window shown in Figure 11.8. This window has a 
menu bar with File, Edit, and Help pulldown menus. When you select a menu item, the result of your 
selection is displayed in the middle of the window. 
MenuAppListing 11.7: The Program 
import java.awt.*; 
import java.awt.event.*; 
public class MenuApp extends Frame { 
MenuBar mb = new MenuBar(); 
Label label = new Label(""); 
public static void main(String[] args) { 
 MenuApp app = new MenuApp(); 
} 
public MenuApp() {
 super("MenuApp")
; 
Panel panel = new Panel()
; 
- 197 
panel.add(label)
; 
add("Center",panel)
; 
addWindowListener(new WindowEventHandler())
; 
setupMenuBar()
; 
setMenuBar(mb)
; 
pack()
; 
setSize(400,400)
; 
show()
; 
} 
 void setupMenuBar() 
{ 
Menu fileMenu = new Menu("File")
; 
Menu editMenu = new Menu("Edit")
; 
Menu helpMenu = new Menu("Help")
; 
MenuItem newFileMenu = new MenuItem("New")
; 
MenuItem exitFileMenu = new MenuItem("Exit")
; 
fileMenu.add(newFileMenu)
; 
fileMenu.addSeparator()
; 
fileMenu.add(exitFileMenu)
; 
MenuItem cutEditMenu = new MenuItem("Cut")
; 
MenuItem copyEditMenu = new MenuItem("Copy")
; 
MenuItem pasteEditMenu = new MenuItem("Paste")
; 
Menu statusMenu = new Menu("Status")
; 
CheckboxMenuItem textMode = new CheckboxMenuItem("Text Mode",true)
; 
CheckboxMenuItem wordWrap = new CheckboxMenuItem("Word Wrap",true)
; 
statusMenu.add(textMode)
; 
statusMenu.add(wordWrap)
; 
editMenu.add(cutEditMenu)
; 
editMenu.add(copyEditMenu)
; 
editMenu.add(pasteEditMenu)
; 
editMenu.addSeparator()
; 
editMenu.add(statusMenu)
; 
- 198 
MenuItem aboutHelp = new MenuItem("About")
; 
helpMenu.add(aboutHelp)
; 
mb.add(fileMenu)
; 
mb.add(editMenu)
; 
mb.setHelpMenu(helpMenu)
; 
MenuHandler mh = new MenuHandler()
; 
newFileMenu.addActionListener(mh)
; 
exitFileMenu.addActionListener(mh)
; 
cutEditMenu.addActionListener(mh)
; 
copyEditMenu.addActionListener(mh)
; 
pasteEditMenu.addActionListener(mh)
; 
textMode.addItemListener(mh)
; 
wordWrap.addItemListener(mh)
; 
aboutHelp.addActionListener(mh)
; 
} 
class MenuHandler implements ActionListener, ItemListener 
{ 
 public void actionPerformed(ActionEvent e)
{ 
String s = e.getActionCommand()
; 
label.setText(s)
; 
validate()
; 
if(s.equals("Exit")) System.exit(0)
; 
} 
 public void itemStateChanged(ItemEvent e)
{ 
CheckboxMenuItem item = (CheckboxMenuItem) e.getItemSelectable()
; 
String status; 
if(item.getState()) status = "You checked: "
; 
else status = "You unchecked: "
; 
status += item.getLabel()
; 
label.setText(status)
; 
validate()
; 
} 
- 199 
} 
 class WindowEventHandler extends WindowAdapter{ 
public void windowClosing(WindowEvent e) { 
System.exit(0); 
} 
} 
} 
Pop-up Menus
In addition to the traditional menus that are pulled down from a menu bar, Java provides support for 
pop-up menus, which are menus that appear when you perform a mouse action that triggers them. 
Pop-up menus are supported via the PopupMenu class, which is a subclass of the Menu class. This 
class provides two constructors—a default parameterless constructor and a constructor that takes a 
String parameter. The String parameter is used as the pop-up menu's title. In Windows, the title is 
not displayed. 
The show() method of the PopupMenu class causes a pop-up menu to be displayed. Its arguments are 
the Component object in which the menu is to be popped up and the x, y coordinate where the menu is 
to be placed (relative to the component). 
Chapter Summary 
This chapter covered the classes and interfaces of java.awt that are used to implement GUI 
components and containers. You were introduced to each of the major AWT components and learned 
how they are organized into containers. You also built several small Java applications and applets that 
illustrated the use of component and containers. You should now be prepared to test your knowledge of 
these topics. The following review questions and exam questions will let you know how well you 
understand this material and will give you an idea of how you'll do in related exam questions. They'll 
also indicate which material you need to study further. 
Key Terms
. 
Abstract Windowing Toolkit 
.. Component 
.. Container 
.. Button 
.. Label 
. 
Text Field 
. 
Text Area 
.. Checkbox 
. 
Radio Button 
. 
Selection List 
.. Window 
.. Frame 
- 200 
. 
Dialog 
. 
Panel 
. 
Applet 
Review Questions 
1. 
Which class is the immediate superclass of the Container class? 
2. 
Which method of the Component class is used to set the position and size of a 
component? 
3. 
Name three subclasses of the Component class. 
4. 
What methods are used to get and set the text label displayed by a Button object? 
5. 
Name two subclasses of the TextComponent class. 
6. 
Which TextComponent method is used to set a TextComponent to the read-only 
state? 
7. 
How can the Checkbox class be used to create a radio button? 
8. 
Name four Container classes. 
9. 
Which class is the immediate superclass of the MenuComponent class. 
10. What Checkbox method allows you to tell if a Checkbox is checked? 
11. What is the difference between a Choice and a List? 
12. Which Container method is used to cause a container to be laid out and redisplayed? 
13. What is the difference between a Window and a Frame? 
14. What is the immediate superclass of the Dialog class? 
15. What is the immediate superclass of the Applet class? 
16. What is the difference between a Scrollbar and a ScrollPane? 
17. Which containers may have a MenuBar? 
18. What is the immediate superclass of Menu? 
19. What is the difference between a MenuItem and a CheckboxMenuItem? 
20. Which Component subclass is used for drawing and painting? 
Exam Questions 
1. 
Which of the following are true? 
A. 
Component extends Container. 
B. 
MenuItem extends Component. 
C. 
Container extends Component. 
D. 
MenuComponent extends Component.
2. 
Which of the following are direct or indirect subclasses of Component? 
A. 
Button 
B. 
Label 
C. 
CheckboxMenuItem 
D. 
Toolbar 
E. 
Frame 
3. 
Which of the following are direct or indirect subclasses of Container? 
A. 
Frame 
B. 
TextArea 
C. 
MenuBar 
D. 
FileDialog
E. 
Applet
4. 
Which Component method is used to access a component's immediate Container? 
A. 
getVisible()
B. 
getImmediate()
C. 
getParent()
D. 
getContainer()
5. 
Which method is used to set the text of a Label object? 
A. 
setText()
B. 
setLabel()
C. setTextLabel()
D. setLabelText() 
- 201 
6. 
Which of the following are true? 
A. 
TextComponent extends TextArea. 
B. 
TextArea extend TextField. 
C. 
TextField extends TextComponent. 
D. 
TextComponent extends TextField. 
E. 
TextArea extends TextComponent. 
7. 
Which of the following are true? 
A. The Checkbox class extends the RadioButton class. 
B. The CheckboxGroup class is used to define radio buttons. 
C. The RadioGroup class is used to define radio buttons. 
D. A Checkbox is a RadioButton that has been associated with a 
CheckboxGroup. 
E. A Checkbox is a RadioButton that has been associated with a 
RadioGroup. 
8. 
Which constructor creates a TextArea with 10 rows and 20 columns? 
A. 
new TextArea(10,20)
B. 
new TextArea(20,10)
C. 
new TextArea(new Rows(10), new Colums(20))
D. 
new TextArea(200)
9. 
Which of the following creates a List with 5 visible items and multiple selection 
enabled? 
A. 
new List(5, true)
B. 
new List(true, 5)
C. 
new List(5, false)
D. 
new List(false, 5)
10. Which are true about the Container class? 
A. The validate() method is used to cause a Container to be laid out 
and redisplayed. 
B. The add() method is used to add a Component to a Container. 
C. The getBorder() method returns information about a container's insets. 
D. The getComponent() method is used to access a Component that is 
contained in a Container. 
11. Which of the following are true? 
A. 
Window extends Frame. 
B. 
Applet extends Window. 
C. 
Panel extends Container. 
D. 
ScrollPane extends Panel. 
12. Which of the following are true? 
A. A Dialog can have a MenuBar. 
B. 
MenuItem extends Menu. 
C. A MenuItem can be added to a Menu. 
D. A Menu can be added to a Menu. 
13. Suppose a Panel is added to a Frame and a Button is added to the Panel. If the 
Frame's font is set to 12-point TimesRoman, the Panel's font is set to 10-point 
TimesRoman, and the Button's font is not set, what font will be used to display the 
Button's label? 
A. 
12-point TimesRoman 
B. 
11-point TimesRoman 
C. 
10-point TimesRoman 
D. 
9-point TimesRoman 
14. A Frame's background color is set to Color.Yellow, and a Button's background 
color is set to Color.Blue. Suppose the Button is added to a Panel, which is added 
to the Frame. What background color will be used with the Panel? 
A. 
Color.Yellow 
B. 
Color.Blue 
C. 
Color.Green 
D. 
Color.White 
- 202 
15. Which methods will cause a Frame to be displayed? 
A. 
show()
B. 
setVisible()
C. 
display()
D. 
displayFrame() 
Answers to Review Questions 
1. 
Component
2. 
setBounds()
3. 
Box.Filler, Button, Canvas, Checkbox, Choice, Container, Label, List, 
Scrollbar, or TextComponent
4. 
getLabel() and setLabel()
5. 
TextField and TextArea 
6. 
setEditable()
7. 
By associating Checkbox objects with a CheckboxGroup. 
8. 
Window, Frame, Dialog, FileDialog, Panel, Applet, or ScrollPane 
9. 
Object
10. getState()
11. A Choice is displayed in a compact form that requires you to pull it down to see the list 
of available choices. Only one item may be selected from a Choice. A List may be 
displayed in such a way that several List items are visible. A List supports the 
selection of one or more List items. 
12. validate()
13. The Frame class extends Window to define a main application window that can have a 
menu bar. 
14. Window 
15. Panel 
16. A Scrollbar is a Component, but not a Container. A ScrollPane is a 
Container. A ScrollPane handles its own events and performs its own scrolling. 
17. Frame 
18. MenuItem 
19. The CheckboxMenuItem class extends the MenuItem class to support a menu item 
that may be checked or unchecked. 
20. Canvas 
Answers to Exam Questions 
1. 
C. The Container class is a subclass of Component. MenuItem extends 
MenuComponent which extends Object. 
2. 
A, B, and E. CheckboxMenuItem is not in the Component class hierarchy. Toolbar is 
not an AWT class. 
3. 
A, D, and E. TextArea and MenuBar are not subclasses of Container. 
4. 
C. The getParent() method is used to access a component's container. 
5. 
A. The setText() method sets the text of a Label. 
6. 
C and E. TextComponent is extended by TextField and TextArea. 
7. 
B. The CheckboxGroup class is used to define radio buttons. 
8. 
A. Usage is TextArea(rows,columns). 
9. 
A. Usage is List(rows, multipleMode). 
10. A, B, and D. The getBorder() method is not defined for the Container class. 
11. C. Panel extends Container. The others are false. 
12. C and D. A MenuItem (and therefore a Menu) can be added to a Menu. 
13. C. Since the Button's parent is the Panel, the Button inherits the Panel's font. 
14. A. The Panel inherits the Frame's background color. 
15. A and B. Either show() or setVisible() may be used.
 
No comments:
Post a Comment