Wednesday, June 27, 2007

Chapter 13 - The java.awt Package: Event Handling

Chapter 13: The java.awt Package: Event Handling

Objectives

This chapter helps you to prepare for the exam by covering the following objectives:

Know how AWT event handling takes place.

.
Event handling enables GUI applications to respond to user actions. A general knowledge of
how event handling is performed is required for the certification exam.

Know the difference between the JDK 1.0 event handling model and that of JDK 1.1 and later.

.
JDK 1.0 supported an event-handling model based on event inheritance or "bubbling." This
model was replaced with an event-delegation model in JDK 1.1. Knowledge of the
differences between the old and new models is needed to correctly answer some exam
questions.
Know which classes and interfaces support the event delegation model.

.
Although you don't need to know all the details about the AWT's event handling classes and
interfaces, the exam assumes that you have a general familiarity with how each is used. You
will be required to recognizes the names of these classes and interfaces and have a basic
familiarity with their constructors, properties, and methods.
Know how listeners and adapters are used in event handling.

.
To build a basic GUI application or applet, you'll need to handle the events that result from
user interaction with the GUI. You need to have some hands-on experience using listeners
and event handlers to correctly answer these exam questions.
Know how to override event dispatching methods.

.
While the preferred way of handling AWT events is through the event-delegation facilities, it
is also possible for a component to explicitly handle its own events by overriding its event-
dispatching methods.
Study Strategies

As you read through this chapter, you should concentrate on the following key items:

.
How the AWT event-delegation model works
.
Which classes and interfaces support event handling
.
How listeners and adapters are used to implement the event-delegation model
.
How to override a component's event-dispatching methods
Chapter Introduction

This chapter covers the event-handling classes and interfaces of java.awt.event, java.awt, and
java.util. Familiarity with these classes and interfaces is essential to writing event handling code. A
few exam questions will test your knowledge of the material covered in this chapter. By studying the
descriptions of the event-handling classes and interfaces presented in this chapter, you'll refresh your
knowledge of event handling and be ready for any related exam questions.

Handling Events

The user communicates with window programs by performing actions such as clicking a mouse button
or pressing a key on the keyboard. These actions result in the generation of events. The process of
responding to an event is known as event handling. The invocation of an event handling method is the
end result of an event's generation. Window programs are said to be event-driven because they operate
by performing actions in response to events.
The JDK 1.02 supported an approach to event handling referred to as an inheritance model. In this
approach, events are handled by subclassing window components and overriding their action(),
handleEvent(), and other methods. These methods return True or False to indicate whether they
have successfully handled an event. If a True value is returned, the event processing is complete.
Otherwise, the event is sent to the object's container for further processing. In this model, a container
inherits all the events that are not handled by its components. The component events are said to bubble
up the containment hierarchy. One of the problems with this approach is that a significant number of
processing resources are expended in bubbling up events that are never handled.
The JDK 1.02 approach to event handling was replaced by an event-delegation model in JDK 1.1.
However, the old inheritance event model was still supported. The old model is now fully deprecated in
Java 2.
The event-delegation model provides the capability to deliver events to programmer-selected classes—
a capability that was lacking in JDK 1.02. The event-delegation approach is less complex and more
efficient. It uses special interfaces, called event listeners, whose methods listen for the occurrence of
events. In this model, a source object generates events that are listened for by a listener object. The
source object is usually a window GUI component, such as a button. The listener object is a class that
implements an event-listener interface appropriate for the source object. The source object provides
methods that allow listener objects to register themselves to listen for its events. For example, an object

- 220



that handles the clicking of a button implements the ActionListener interface. This object is
registered with a particular button via the button's addActionListener() method.

The event-delegation model is a significant improvement over that of Java 1.02, which required GUI
components to be subclassed in order to handle events. Although it is still possible to do this in the
event-delegation model, it is no longer necessary. Events can be handled by classes that are separate
from the component in which the event is generated.

Handling Events

The user communicates with window programs by performing actions such as clicking a mouse button
or pressing a key on the keyboard. These actions result in the generation of events. The process of
responding to an event is known as event handling. The invocation of an event handling method is the
end result of an event's generation. Window programs are said to be event-driven because they operate
by performing actions in response to events.
The JDK 1.02 supported an approach to event handling referred to as an inheritance model. In this
approach, events are handled by subclassing window components and overriding their action(),
handleEvent(), and other methods. These methods return True or False to indicate whether they
have successfully handled an event. If a True value is returned, the event processing is complete.
Otherwise, the event is sent to the object's container for further processing. In this model, a container
inherits all the events that are not handled by its components. The component events are said to bubble
up the containment hierarchy. One of the problems with this approach is that a significant number of
processing resources are expended in bubbling up events that are never handled.
The JDK 1.02 approach to event handling was replaced by an event-delegation model in JDK 1.1.
However, the old inheritance event model was still supported. The old model is now fully deprecated in
Java 2.
The event-delegation model provides the capability to deliver events to programmer-selected classes—
a capability that was lacking in JDK 1.02. The event-delegation approach is less complex and more
efficient. It uses special interfaces, called event listeners, whose methods listen for the occurrence of
events. In this model, a source object generates events that are listened for by a listener object. The
source object is usually a window GUI component, such as a button. The listener object is a class that
implements an event-listener interface appropriate for the source object. The source object provides
methods that allow listener objects to register themselves to listen for its events. For example, an object
that handles the clicking of a button implements the ActionListener interface. This object is
registered with a particular button via the button's addActionListener() method.

The event-delegation model is a significant improvement over that of Java 1.02, which required GUI
components to be subclassed in order to handle events. Although it is still possible to do this in the
event-delegation model, it is no longer necessary. Events can be handled by classes that are separate
from the component in which the event is generated.

The JDK 1.02 Event Class

In the JDK 1.02 inheritance model, the Event class encapsulates all Windows event processing. The
Event class defines the entire list of events handled by window programs using class constants. These
constants are used to identify the events that are passed to event-handling methods. You can review
the Java API description of the Event class to familiarize yourself with these constants.
The Event class provides three constructors for creating events, but you probably won't need to use
these constructors because events are internally generated by the Java runtime system in response to
user interface actions. The Event class also provides methods for determining whether the Ctrl, Shift,
or Meta (Alt) keys are pressed during the generation of an event.

The Classes and Interfaces of the Event Delegation Model

In the event-delegation model that was introduced with JDK 1.1 (and extended in Java 2), the
java.util.EventObject class is the top-level class of the event-class hierarchy. This class provides
a source field variable to identify the object that is the source of an event, a getSource() method to
retrieve this object, and a toString() method to convert an event into a String representation. It
provides a single constructor that takes the object that is the source of the event as an argument.
The java.awt.AWTEvent class extends the java.util.EventObject class to support AWT
events. It provides several variables, constants, and methods that are used to identify events and
determine whether they are consumed. The AWTEvent class is extended by the following classes of
java.awt.event:

- 221



.
ActionEvent—Generated by user interface actions, such as clicking on a button or
selecting a menu item.
.
AdjustmentEvent—Generated by scrolling actions.
.
AncestorEvent—Generated when the ancestor of a component is added or removed from
visibility or moved.
.
ComponentEvent—Generated by changes to the position, focus, or sizing of a window
component, or by a keyboard input or other mouse action.
.
InputMethodEvent—Generated by changes to the text being entered via an input
method.
.
InternalFrameEvent—Generated as the result of changes to a SwingJInternalEvent object. (Knowledge of Swing is not required

for the certification exam.)
.
InvocationEvent—Generated by the invokeLater() and invokeAndWait(
)
methods of the EventQueue object.
.
ItemEvent—Generated by a component-state change, such as selecting an item from a
list.
.
TextEvent—Generated by text-related events, such as changing the value of a text field.
The ComponentEvent class is further extended by the following classes:
.
FocusEvent—Generated by a change in the status of a component's input focus
.
InputEvent—Subclassed by KeyEvent and MouseEvent to cover events generated by
keyboard actions and low-level mouse events
.
ContainerEvent—Generated by events associated with adding and removing
components from a container
.
PaintEvent—Generated by the painting/repainting of a window
.
WindowEvent—Generated by events such as the opening, closing, and minimizing of a
window
The AWTEvent class and its subclasses enable window-related events to be directed to specific objects
that listen for those events. These objects implement EventListener interfaces. The
java.util.EventListener interface is the top-level interface of the event-listener hierarchy. It is an
interface in name only because it does not define any constants or methods. It is extended by the
following interfaces of java.awt.event:

.
ActionListener—Implemented by objects that handle ActionEvent events
.
AWTEventListener—Implemented by objects that monitor AWTEvent events
.
AdjustmentListener—Implemented by objects that handle AdjustmentEvent events
.
ComponentListener—Implemented by objects that handle ComponentEvent events
.
ContainerListener—Implemented by objects that handle ContainerEvent events
.
FocusListener—Implemented by objects that handle FocusEvent events
.
InputMethodListener—Implemented by objects that handle InputMethodEvent
events
.
ItemListener—Implemented by objects that handle ItemEvent events
.
KeyListener—Implemented by objects that handle KeyEvent events
.
MouseListener—Implemented by objects that handle clicking-related MouseEvent
events
.
MouseMotionListener—Implemented by objects that handle movement-related
MouseEvent events
.
TextListener—Implemented by objects that handle TextEvent events
.
WindowListener—Implemented by objects that handle WindowEvent events
As a convenience, the java.awt.event package provides event adapter classes that implement the
event listener interfaces. These classes may be subclassed to override specific event-handling methods
of interest. The adapter classes of java.awt.event are as follows:
.
ComponentAdapter—Implements the ComponentListener interface and handles
ComponentEvent events
.
ContainerAdapter—Implements the ContainerListener interface and handles
ContainerEvent events
.
FocusAdapter—Implements the FocusListener interface and handles FocusEvent
events
.
KeyAdapter—Implements the KeyListener interface and handles KeyEvent events
.
MouseAdapter—Implements the MouseListener interface and handles clicking-related
MouseEvent events
- 222



.
MouseMotionAdapter—Implements the MouseListener interface and handles
movement-related MouseEvent events
.
WindowAdapter—Implements the WindowListener interface and handles
WindowEvent events
These adapter classes are convenience classes because they provide stubs for the methods of the
interfaces that you don't want to implement yourself.
In addition to the classes and interfaces covered so far in this section, the following two classes of
java.awt also support the event-delegation model:


.
java.awt.EventQueue—supports the queuing of events. It enables event listeners to
monitor the queue and retrieve specific events for processing. The EventQueue is
automatically created and managed by the runtime system to queue the events generated
by GUI components.
.
java.awt.AWTEventMulticaster—provides the capability to listen for multiple events
and then forward the events to multiple-event listeners. It provides a thread-safe mechanism
by which event listeners can be added and removed from its event-listening destination list.
An object may handle the events of more than one object. Conversely, an object may have one of its
events handled by more than one event-handling object. In the latter case, the order of invocation of the
event handlers cannot be predicted.

An Event Delegation Example

Now that you've covered the event-handling classes and interfaces, let's work through a programming
example so that you can see how they are used in a window application. Listing 13.1 presents the Event
Sampler program. This program shows how the events of common AWT components are handled.
When you run EventApp, it displays the window shown in Figure 13.1. It provides samples of the
following GUI components:

.
Text field Typing Enter in the text field causes the contents of the text field to be converted to
uppercase.
.
Text area The text area is used to display the results of handling the events of the other GUI
components.
.
Button Clicking the button clears the contents of the text area.
..Canvas Clicking in the canvas results in a little red square being displayed.
Figure 13.1: The Event Sampler default window.

.
Check box Checking the check boxes results in text being displayed in the associated text
field.
.
Choice The selection of a choice is displayed in the text area.
- 223



.
List Selection of a list item is displayed in the text area. Double-clicking of a list item also
updates the text area.
.
Horizontal scrollbar Any change to the horizontal scrollbar is displayed in the text area.
.
Vertical scrollbar Any change to the vertical scrollbar is displayed in the text area.
EventappListing 13.1: The Program

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

public class EventApp extends Frame {
// Used to display the results of event handling.
TextArea textArea;
public static void main(String args[]){

EventApp app = new EventApp()
;
}
public EventApp()
{


super("Event Sampler")
;
setup()
;
setSize(480,480)
;
// Add event handler for closing the frame.
addWindowListener(new WindowEventHandler())
;
show()
;


}


void setup()
{
setupMenuBars()
;
setupPanels()
;


}


void setupMenuBars()
{
MenuBar menuBar = new MenuBar()
;
Menu fileMenu = new Menu("File")
;
MenuItem fileExit = new MenuItem("Exit")
;
MenuItemHandler mh = new MenuItemHandler()
;


- 224



// Add an action listener for File -> Exit.
fileExit.addActionListener(mh);
fileMenu.add(fileExit);
menuBar.add(fileMenu);
setMenuBar(menuBar);

}

void setupPanels() {
Panel mainPanel = new Panel();
// Divide the main panel into a 3-by-3 grid.
mainPanel.setLayout(new GridLayout(3,3));
// Create each of the subpanels.
Panel panels[][] = new Panel[3][3];
for(int i=0;i<3;++i){

for(int j=0;j<3;++j){
panels[j][i] = new Panel();
panels[j][i].setLayout(new FlowLayout(FlowLayout.LEFT));

}
}
// Set up the text field
panels[0][0].add(new Label("Text Field:"));
TextField textField = new TextField("A text field.",15);
// Handle the text field's action event
textField.addActionListener(new HandleTextField());
panels[0][0].add(textField);
// Set up the text area
panels[1][0].add(new Label("Text Area:"));
textArea = new TextArea("A text area.",5,15);
panels[1][0].add(textArea);
// Set up the button
panels[2][0].add(new Label("Button:"));

- 225



Button button = new Button("Blank Text Area")
;
// Handle the button's action event.
button.addActionListener(new HandleButton())
;
panels[2][0].add(button)
;
// Set up the canvas. It handles its own events.
panels[0][1].add(new Label("Canvas:"))
;
panels[0][1].add(new MyCanvas())
;
// Set up the checkbox panel. It also handles its own events.
String checkboxStrings[] = {"Checkboxes:","Java","2","Certification"}
;
panels[1][1].add(new MyCheckboxGroup(checkboxStrings))
;
// Set up the choice component.
panels[2][1].add(new Label("Choices:"))
;
String choiceStrings[] = {"Yes","No","Maybe"}
;
Choice choice = new Choice()
;
for(int i=0;i

choice.addItem(choiceStrings[i])
;
// Handle the selection of a choice.
choice.addItemListener(new HandleChoice())
;
panels[2][1].add(choice)
;
// Set up the list.
panels[0][2].add(new Label("List:"))
;
String listStrings[] = {"Sleepy","Sneezy","Grumpy","Dopey","Doc"
,


"Happy","Bashful"}
;
List list = new List(3,false)
;
for(int i=0;i

list.add(listStrings[i])
;
// Handle the selection and double-click events.
list.addItemListener(new HandleListSelect())
;
list.addActionListener(new HandleListDoubleClick())
;
panels[0][2].add(list)
;
// Set up the horizontal scrollbar.


- 226



panels[1][2].setLayout(new BorderLayout())
;
panels[1][2].add("Center",new Label("Horizontal Scrollbar:"))
;
Scrollbar hScroll = new Scrollbar(Scrollbar.HORIZONTAL,50,10,0,100)
;
// Handle the scrollbar's adjustment event.
hScroll.addAdjustmentListener(new HandleScrolling())
;
panels[1][2].add("South",hScroll)
;
// Set up the vertical scrollbar.
panels[2][2].setLayout(new BorderLayout())
;
panels[2][2].add("North",new Label("Vertical Scrollbar:"))
;
Scrollbar vScroll = new Scrollbar(Scrollbar.VERTICAL,50,10,0,1000)
;
// Handle the scrollbar's adjustment event.
vScroll.addAdjustmentListener(new HandleScrolling())
;
panels[2][2].add("East",vScroll)
;
for(int i=0;i<3;++i)


for(int j=0;j<3;++j)
mainPanel.add(panels[j][i])
;


add("Center",mainPanel)
;
}
class WindowEventHandler extends WindowAdapter
{


// Handle the window's closing
public void windowClosing(WindowEvent e)
{
System.exit(0)
;


}
}
class MenuItemHandler implements ActionListener
{


// Handle menu selections


public void actionPerformed(ActionEvent ev)
{
String s=ev.getActionCommand()
;
if(s.equals("Exit")) System.exit(0)
;


}
}


- 227



class HandleTextField implements ActionListener {
// Handle changes to the text field
public void actionPerformed(ActionEvent ev){

TextField textField = (TextField) ev.getSource()
;
String text = textField.getText()
;
textField.setText(text.toUpperCase())
;



}
}
class HandleButton implements ActionListener
{


// Handle the clicking of a button
public void actionPerformed(ActionEvent ev)
{
textArea.setText("")
;


}
}
class HandleChoice implements ItemListener
{


// Handle a choice selection


public void itemStateChanged(ItemEvent e)
{
Choice ch = (Choice) e.getItemSelectable()
;
textArea.setText(ch.getSelectedItem())
;


}
}
class HandleListSelect implements ItemListener
{


// Handle a list selection


public void itemStateChanged(ItemEvent e)
{
int change = e.getStateChange()
;
List l = (List) e.getItemSelectable()
;
if(change==ItemEvent.SELECTED)
{


textArea.setText("Selected:\n"+l.getSelectedItem())
;
}else if(change==ItemEvent.DESELECTED)
{
textArea.setText("Selected:")
;


- 228



}


}
}
class HandleListDoubleClick implements ActionListener
{


// Handle the double-clicking of a list item
public void actionPerformed(ActionEvent e)
{
textArea.setText("Double-clicked:\n "+e.getActionCommand())
;


}
}
class HandleScrolling implements AdjustmentListener
{


// Handle scrolling
public void adjustmentValueChanged(AdjustmentEvent e)
{
textArea.setText("Position: "+e.getValue())
;
}


}
}
class MyCanvas extends Canvas {

int x = -1;
int y = -1;
int boxSize = 10;
public MyCanvas() {

super()
;
setSize(100,100)
;
setVisible(true)
;
addMouseListener(new MouseHandler())
;
repaint()
;


}

public void paint(Graphics g) {
setBackground(Color.gray);
setForeground(Color.red);
if(x>=0 && y>=0) g.fillRect(x,y,boxSize,boxSize);

- 229



}
class MouseHandler extends MouseAdapter
{


public void mouseClicked(MouseEvent ev)
{
x = ev.getX()
;
y = ev.getY()
;
repaint()
;


}


}
}
class MyCheckboxGroup extends Panel
{


String labelString;
String checkboxLabels[]
;
Checkbox checkboxes[]
;
int numBoxes;
TextField results;
public MyCheckboxGroup(String strings[])
{


super()
;
labelString = strings[0]
;
numBoxes = strings.length-1;
checkboxLabels = new String[numBoxes]
;
for(int i=0;i

checkboxLabels[i] = strings[i+1]
;
results = new TextField("",15)
;
setupPanel()
;
setVisible(true)
;


}

void setupPanel() {
setLayout(new GridLayout(numBoxes+2,1));
add(new Label(labelString));
checkboxes = new Checkbox[numBoxes];
MyCheckboxGroup.HandleCheck hrc =

- 230



new MyCheckboxGroup.HandleCheck();

for(int i=0;icheckboxes[i] = new Checkbox(checkboxLabels[i]);
checkboxes[i].addItemListener(hrc);
add(checkboxes[i]);

}

add(results);
}
class HandleCheck implements ItemListener {

public void itemStateChanged(ItemEvent e){
String newResults = "";
for(int i=0;i
if(checkboxes[i].getState())
newResults = newResults + " " +checkboxes[i].getLabel();
results.setText(newResults);
}
}

}
EventApp provides you with numerous examples of event handling. You should work your way through
the program code and study the operation of the following event handlers:

.
WindowEventHandler Extends the WindowAdapter class and overrides its
windowClosing() method to handle the closing of the application window.
.
MenuItemHandler Implements the ActionListener interface. Uses the
getActionCommand() method of the ActionEvent class to get the label of the selected
menu item.
.
HandleTextField Implements the ActionListener interface. Sets the text field to its
contents converted to uppercase. The getSource() method of the
java.util.EventObject class is used to obtain a reference to the text field.
.
HandleButton Implements the ActionListener interface. Sets the text area to a blank
string.
.
HandleChoice Implements the ItemListener interface. Sets the text area to the
selected item. This item is retrieved through the getSelectedItem() method of the
ItemEvent class.
.
HandleListSelect Implements the ItemListener interface. Sets the text area to the
selected item. This item is retrieved through the getSelectedItem() method of the
ItemEvent class.
.
HandleListDoubleClick Implements the ActionListener interface. Sets the text area
to the clicked item. This item is retrieved through the getActionCommand() method of the
ActionEvent class.
- 231



.
HandleScrolling Implements the AdjustmentListener interface. Sets the text area to
the scrollbar's current position.
.
MouseHandler Extends the MouseAdapter class. Sets the x and y variables to the
location of the mouse click and invokes the repaint() method to cause the canvas to be
redisplayed with the results of the mouse click.
.
HandleCheck Implements ItemListener by displaying the check boxes' labels in a text
field. It uses the getState() method of the Checkbox class to determine which check box
is checked.
Note that the EventApp, MyCanvas, and MyCheckboxGroup classes handle their events using inner
classes. The other event handlers are inner classes of EventApp, but they handle the events of other
GUI components.

Overriding a Component's Event Dispatcher

A GUI component may handle its own events by simply implementing the associated event-handling
interfaces. However, it is also possible to extend the component's class and override its event
dispatching methods. AWT components have methods of the form processXEvent(), where X refers
to the event generated by the component. These methods dispatch events to the appropriate event
listeners. You can override these methods to control the way in which events are dispatched. For
example, the Button class uses the processActionEvent() method to dispatch ActionEvents to
event listeners. You can override processActionEvent() in a subclass of Button to control how
event dispatching takes place.
In addition to overriding the component's event-dispatching method, you may also need to enable the
event. This automatically takes place when an event listener is added to a component. However, if you
do not add an event listener for the component, you'll have to invoke its enableEvents() method,
passing the event identifier (defined in the AWTEvent class) as an argument. For example, to enable
the ActionEvent in an object that is a subclass of Button, you invoke the following method for that
object:


object.enableEvents(AWTEvent.ACTION_EVENT_MASK)
;
The API description of the AWTEvent class lists and describes the event mask constants that are used
with enableEvents(). These constants are of the form EVENTNAME_EVENT_MASK.
Listing 13.2 (EventOverrideApp) provides an example of overriding the processActionEvent(
)
method of the Button class. When the button is clicked, it displays a message in the text area as
shown in Figure 13.2.
Note how the MyButton constructor uses the enableEvents() method to enable the action event
and how the processActionEvent() method performs the event handling.



Figure 13.2: The EventOverrideApp program displays the results of the button click in the text area.

Listing 13.2: The Eventoverrideapp Program


- 232



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

public class EventOverrideApp extends Frame {
public static void main(String args[]){

EventOverrideApp app = new EventOverrideApp()
;
}
public EventOverrideApp()
{


super("Event Override")
;
setup()
;
setSize(300,300)
;
// Add event handler for closing the frame.
addWindowListener(new WindowEventHandler())
;
show()
;


}


void setup()
{
setupMenuBars()
;
setupPanels()
;


}


void setupMenuBars()
{
MenuBar menuBar = new MenuBar()
;
Menu fileMenu = new Menu("File")
;
MenuItem fileExit = new MenuItem("Exit")
;
MenuItemHandler mh = new MenuItemHandler()
;
// Add an action listener for File -> Exit.
fileExit.addActionListener(mh)
;
fileMenu.add(fileExit)
;
menuBar.add(fileMenu)
;
setMenuBar(menuBar)
;


}
void setupPanels() {

- 233



Panel panel = new Panel()
;
TextArea textArea = new TextArea(15,20)
;
MyButton button = new MyButton("Click here!",textArea)
;
panel.add(button)
;
panel.add(textArea)
;
add(panel)
;


}
class WindowEventHandler extends WindowAdapter {
public void windowClosing(WindowEvent e){
System.exit(0);

}
}
class MenuItemHandler implements ActionListener {

public void actionPerformed(ActionEvent ev)
{
String s=ev.getActionCommand()
;
if(s.equals("Exit")) System.exit(0)
;


}

}

}

class MyButton extends Button {
TextArea textArea;
public MyButton(String s, TextArea textArea) {
super(s);
this.textArea = textArea;
enableEvents(AWTEvent.ACTION_EVENT_MASK);
}
public void processActionEvent(ActionEvent event) {
String s = textArea.getText();
s += "\nThe button was clicked.";
textArea.setText(s);
// super.processActionEvent(event);

- 234



// Uncomment the above line to allow event listeners to

// also handle this event.

}

}

Chapter Summary

This chapter covered the classes and interfaces that support AWT event handling. You were introduced
to each of the major AWT events and learned how they are handled using event listeners and adapters.
You also learned how to enable components to handle their own events by overriding their event-
dispatching methods. You should now be prepared to test your knowledge of these topics. The following
review and exam questions will let you know how well you understand this material and give you an
idea of how you'll do on the certification exam. These questions will also indicate what material you
need to study further.

Key Terms

.
Event handling
.
Event inheritance model
.
Event bubbling
.
Event delegation model
.
Event listener
.
Event adapter
Review Questions

1.
What is the difference between the JDK 1.02 event model and the event-delegation
model introduced with JDK 1.1?
2.
What is the highest-level event class of the event-delegation model?
3.
What interface is extended by AWT event listeners?
4.
What class is the top of the AWT event hierarchy?
5.
What event results from the clicking of a button?
6.
What is the relationship between an event-listener interface and an event-adapter class?
7.
In which package are most of the AWT events that support the event-delegation model
defined?
8.
How can a GUI component handle its own events?
9.
What is the advantage of the event-delegation model over the earlier event-inheritance
model?
10. What is the purpose of the enableEvents() method?
Exam Questions

1.
Which of the following are true?
A.
The event-inheritance model has replaced the event-delegation model.
B.
The event-inheritance model is more efficient than the event-delegation
model.
C.
The event-delegation model uses event listeners to define the methods of
event-handling classes.
D.
The event-delegation model uses the handleEvent() method to support
event handling.
2. Which of the following is the highest class in the event delegation class hierarchy?
A.
java.util.EventListener
B.
java.util.EventObject
- 235



C.
java.awt.AWTEvent
D.
java.awt.event.AWTEvent
3.
Which of the following are true?
A.
Event listeners are interfaces that define the methods that event-handling
classes must implement.
B.
An event adapter is a class that provides a default implementation of an
event listener.
C.
The event listener and adapter classes are deprecated in Java 2.
D. The WindowAdapter class is used to handle window-related events.
4.
When two or more objects are added as listeners for the same event, which listener is
first invoked to handle the event?
A.
The first object that was added as a listener.
B.
The last object that was added as a listener.
C.
There is no way to determine which listener will be invoked first.
D.
It is impossible to have more than one listener for a given event.
5.
Which of the following components generate action events?
A. Buttons
B. Labels
C.
Check boxes
D. Windows
6.
Which of the following are true?
A. A TextField object may generate an ActionEvent.
B. A TextArea object may generate an ActionEvent.
C. A Button object may generate an ActionEvent.
D. A MenuItem object may generate an ActionEvent.
7.
Which of the following are true?
A. The MouseListener interface defines methods for handling mouse clicks.
B. The MouseMotionListener interface defines methods for handling
mouse clicks.
C. The MouseClickListener interface defines methods for mouse clicks.
D. The ActionListener interface defines methods for handling the clicking
of a button.
8.
Suppose that you want to have an object eh handle the TextEvent of a TextArea
object t. How should you add eh as the event handler for t?
A.
t.addTextListener(eh);
B.
eh.addTextListener(t);
C.
addTextListener(eh,t);
D.
addTextListener(t,eh);
9.
What is the preferred way to handle an object's events in Java 2?
A. Override the object's handleEvent() method.
B.
Add one or more event listeners to handle the events.
C.
Have the object override its processEvent() methods.
D.
Have the object override its dispatchEvent() methods.
10. Which of the following are true?
A.
A component may handle its own events by adding itself as an event
listener.
B.
A component may handle its own events by overriding its event-dispatching
method.
C.
A component may not handle its own events.
D.
A component may handle its own events only if it implements the
handleEvent() method.
- 236



Answers to Review Questions

1.
The JDK 1.02 event model uses an event inheritance or bubbling approach. In this
model, components are required to handle their own events. If they do not handle a
particular event, the event is inherited by (or bubbled up to) the component's container.
The container then either handles the event or it is bubbled up to its container and so
on, until the highest-level container has been tried.
In the event-delegation model, specific objects are designated as event handlers for GUI
components. These objects implement event-listener interfaces. The event-delegation
model is more efficient than the event-inheritance model because it eliminates the
processing required to support the bubbling of unhandled events.

2.
The java.util.EventObject class is the highest-level class in the event-delegation
class hierarchy.
3.
All AWT event listeners extend the java.util.EventListener interface.
4.
The java.awt.AWTEvent class is the highest-level class in the AWT event-class
hierarchy.
5.
The ActionEvent event is generated as the result of the clicking of a button.
6.
An event-listener interface defines the methods that must be implemented by an event
handler for a particular kind of event. An event adapter provides a default
implementation of an event-listener interface.
7.
Most of the AWT-related events of the event-delegation model are defined in the
java.awt.event package. The AWTEvent class is defined in the java.awt package.
8.
A component can handle its own events by implementing the required event-listener
interface and adding itself as its own event listener.
9.
The event-delegation model has two advantages over the event-inheritance model. First,
it enables event handling to be handled by objects other than the ones that generate the
events (or their containers). This allows a clean separation between a component's
design and its use. The other advantage of the event-delegation model is that it
performs much better in applications where many events are generated. This
performance improvement is due to the fact that the event-delegation model does not
have to repeatedly process unhandled events, as is the case of the event-inheritance
model.
10. The enableEvents() method is used to enable an event for a particular object.
Normally, an event is enabled when a listener is added to an object for a particular
event. The enableEvents() method is used by objects that handle events by
overriding their event-dispatch methods.
Answers to Exam Questions

1.
C. The event-delegation model uses event listeners to define the methods of event-
handling classes. It does not make use of the handleEvent() method of the older,
less-efficient event-inheritance model.
2.
B. The java.util.EventObject class is at the top of the event-delegation class
hierarchy.
3.
A, B, and D. Answer C is false because event-listener and adapter classes are used by
the event-delegation model, which is the preferred approach to Java 2 event handling.
4.
C. When more than one event listener is added for an event, there is no way to
determine which listener will be invoked first.
5.
A. Buttons generate ActionEvents. Labels, Checkboxes, and Windows do not.
6.
A, C, and D. TextAreas do not generate ActionEvents. But, TextFields, Buttons,
and MenuItems do.
7.
A and D. The MouseListener interface handles general mouse clicks. However, the
ActionListener interface handles the clicking of Button objects.
8.
A. You must invoke the TextArea object's addTextListener() method and pass it a
reference to the event handler.
9.
B. The event-delegation model uses event listeners to handle events.
10. A and B. A component may handle its own events by adding itself as an event handler
or overriding its event-dispatching method.

No comments: