Java Reference
In-Depth Information
More on listeners
9
In this chapter we discuss how to use listeners in general. We also introduce some
more listeners that react to events not considered so far. This chapter can be skipped
in a first reading.
9.1
Basics of listeners
Listeners are those components that link user actions to a running program. There
are different listeners for different types of user actions. We have seen examples in
Chapters 3, 4 and 6. These react to pressing a button or to using the mouse. There
are many more listeners, some of which we shall briefly introduce here. Look in
the java.awt.event library to see more.
A listener has to be assigned to a graphical component. The components have
methods
addXXXXXXListener(XXXXXXListener listener)
for doing this, where XXXXXX is the type of the listener, e.g. MouseMotion . All
listeners are interfaces . They require certain methods to be implemented by the
programmer, e.g. mouseMoved . These methods are then automatically called by
the operating system if the related event occurs, e.g. the mouse is moved. The
code for the application's reaction to an event therefore has to be inside these
methods.
Some listeners have only one method, such as actionPerformed in Action-
Listener s, while others have more, like the five methods of a MouseListener .
Every one of them reacts to a different event. If one only wants a reaction to some
events, then the other methods are implemented with an empty body.
The methods of listener receive an event object as an argument. This event
object contains more information about the event. Different listeners have differ-
ent kinds of event objects ( ActionEvent for ActionListener s, MouseEvent for
MouseListener s). The event object is automatically generated by the runtime
system when an event occurs and the appropriate method of the listener is called.
The information in the various types of events varies. A MouseEvent contains
the coordinates at which the mouse pointer was when the event occurred. For an
Search WWH ::




Custom Search