Java Reference
In-Depth Information
LISTING 12.1
Continued
22:
23: public void actionPerformed(ActionEvent evt) {
24: Object source = evt.getSource();
25: if (source == b1) {
26: setTitle(“Rosencrantz”);
27: } else if (source == b2) {
28: setTitle(“Guildenstern”);
29: }
30: repaint();
31: }
32:
33: public static void main(String[] arguments) {
34: TitleChanger frame = new TitleChanger();
35: }
36: }
After you run this application with the Java interpreter, the program's interface should
resemble Figure 12.1.
FIGURE 12.1
The
TitleChanger
application.
Only 12 lines were needed to respond to action events in this application:
Line 1 imports the
java.awt.event
package.
n
Line 5 implements the
ActionListener
interface.
n
Lines 12 and 13 add action listeners to both
JButton
objects.
n
Lines 23-31 respond to action events that occur from the two
JButton
objects. The
evt
object's
getSource()
method determines the source of the event. If it is equal
to the
b1
button, the title of the frame is set to
Rosencrantz
; if it is equal to
b2
, the
title is set to
Guildenstern
. A call to
repaint()
is needed so that the frame is
redrawn after any title change that might have occurred in the method.
n
The following sections detail the structure of each event-handling method and the meth-
ods that can be used within them.