Java Reference
In-Depth Information
Let's revisit Listing 16.1, HandleEvent.java. Since a
JButton
object fires
ActionEvent
,
a listener object for
ActionEvent
must be an instance of
ActionListener
, so the listener
class implements
ActionListener
in line 34. The source object invokes
addActionListener(listener)
to register a listener, as follows:
JButton jbtOK =
new
JButton(
"OK"
);
// Line 7 in Listing 16.1
create source object
OKListenerClass listener1
=
new
OKListenerClass();
// Line 18 in Listing 16.1
create listener object
jbtOK.addActionListener(listener1);
// Line 20 in Listing 16.1
register listener
When you click the button, the
JButton
object fires an
ActionEvent
and passes it to invoke
the listener's
actionPerformed
method to handle the event.
The event object contains information pertinent to the event, which can be obtained using
the methods, as shown in Figure 16.7. For example, you can use
e.getSource()
to obtain
the source object that fired the event. For an action event, you can use
e.getWhen()
to
obtain the time when the event occurred.
java.util.EventObject
+getSource(): Object
Returns the source object for the event.
java.awt.event.AWTEvent
java.awt.event.ActionEvent
+getActionCommand(): String
Returns the command string associated with this action. For a
button, its text is the command string.
Returns the modifier keys held down during this action event.
Returns the timestamp when this event occurred. The time is the
+getModifiers(): int
+getWhen(): long
number of milliseconds since January 1, 1970, 00:00:00 GMT.
F
IGURE
16.7
You can obtain useful information from an event object.
We now write a program that uses two buttons to control the size of a circle, as shown in
Figure 16.8.
F
IGURE
16.8
The user clicks the
Enlarge
and
Shrink
buttons to enlarge and shrink the size
of the circle.
We will develop this program incrementally. First we will write the program in Listing 16.2
that displays the user interface with a circle in the center (line 14) and two buttons on the bot-
tom (line 15).
first version