Java Reference
In-Depth Information
A
JButton
generates an
action event
when it is pushed. Therefore the listener
class we write will be an action event listener. In this program, we define a class
called
ButtonListener
to represent the listener for this event.
We could write the
ButtonListener
class in its own file,
or even in the same file but outside of the
PushCounterPanel
class. However, then we would have to set up a way to
communicate between the listener and the components of
the GUI that the listener updates. Instead, we define the
ButtonListener
class as an
KEY CONCEPT
Listeners are often defined as inner
classes because of the intimate rela-
tionship between the listener and the
GUI components.
inner class,
which is a class
defined within another class. As such, it automatically has access to the members
of the class that contains it. You should create inner classes only in situations in
which there is an intimate relationship between the two classes and in which the
inner class is not accessed by any other class. The relationship between a listener
and its GUI is one of the few situations in which an inner class is appropriate.
Listener classes are written by implementing an
interface,
which is a list
of methods that the implementing class must define. The Java standard class
library contains interfaces for many types of events. An action listener is cre-
ated by implementing the
ActionListener
interface; therefore, we include the
implements
clause in the
ButtonListener
class. Interfaces are discussed in
more detail in Chapter 7.
The only method listed in the
ActionListener
interface is the
actionPerformed
method, so that's the only method that the
ButtonListener
class must implement. The component that generates the action event (in this case
the button) will call the
actionPerformed
method when the event occurs, pass-
ing in an
ActionEvent
object that represents the event. Sometimes we will use the
event object, and other times it is simply sufficient to know that the event
occurred. In this case, we have no need to interact with the event object. When
the event occurs, the listener increments the
count
and resets the text of the label
by using the
setText
method.
Remember, we not only have to create a listener for an event, we must also set
up the relationship between the listener and the component that will generate the
event. To do so, we add the listener to the component by calling the appropriate
method. In the
PushCounterPanel
constructor, we call the
addActionListener
method, passing in a newly instantiated
ButtonListener
object.
Review this example carefully, noting how it accomplishes the three key
steps to creating an interactive GUI-based program. It creates and sets up the
GUI components, creates the appropriate listener for the event of interest,
and sets up the relationship between the listener and the component that will
generate the event.
Search WWH ::
Custom Search