Some sources may allow only one listener to register. The general form of such a method
public void addTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. When such
an event occurs, the registered listener is notified. This is known as unicasting the event.
A source must also provide a method that allows a listener to unregister an interest
in a specific type of event. The general form of such a method is this:
public void removeTypeListener(TypeListener el)
Here, Type is the name of the event, and el is a reference to the event listener. For example,
to remove a keyboard listener, you would call removeKeyListener( ).
The methods that add or remove listeners are provided by the source that generates
events. For example, the Component class provides methods to add and remove keyboard
and mouse event listeners.
A listener is an object that is notified when an event occurs. It has two major requirements.
First, it must have been registered with one or more sources to receive notifications about
specific types of events. Second, it must implement methods to receive and process these
The methods that receive and process events are defined in a set of interfaces found in
java.awt.event. For example, the MouseMotionListener interface defines two methods to
receive notifications when the mouse is dragged or moved. Any object may receive and process
one or both of these events if it provides an implementation of this interface. Many other
listener interfaces are discussed later in this and other chapters.
The classes that represent events are at the core of Java's event handling mechanism. Thus, a
discussion of event handling must begin with the event classes. It is important to understand,
however, that Java defines several types of events and that not all event classes can be discussed
in this chapter. The most widely used events are those defined by the AWT and those defined by
Swing. This chapter focuses on the AWT events. (Most of these events also apply to Swing.)
Several Swing-specific events are described in Chapter 29, when Swing is covered.
At the root of the Java event class hierarchy is EventObject, which is in java.util. It is the
superclass for all events. Its one constructor is shown here:
Here, src is the object that generates this event.
EventObject contains two methods: getSource( ) and toString( ). The getSource( ) method
returns the source of the event. Its general form is shown here:
Object getSource( )
As expected, toString( ) returns the string equivalent of the event.
Search WWH :