Java Reference
In-Depth Information
The quitProgram() method is called if the quitButton object generated the event, and
the sortRecords() method is called if the sortRecords button generated the event.
Many event-handling methods call a different method for each kind of event or compo-
nent. This makes the event-handling method easier to read. In addition, if there is more
than one event-handling method in a class, each one can call the same methods to get
work done.
The instanceof operator can be used in an event-handling method to determine what
class of component generated the event. The following example can be used in a pro-
gram with one button and one text field, each of which generates an action event:
void actionPerformed(ActionEvent event) {
Object source = event.getSource();
if (source instanceof JTextField) {
calculateScore();
} else if (source instanceof JButton) {
quitProgram();
}
}
The program in Listing 12.1 is a frame with two JButton components, which are used to
change the text on the frame's title bar.
LISTING 12.1
The Full Text of TitleChanger.java
1: import java.awt.event.*;
2: import javax.swing.*;
3: import java.awt.*;
4:
5: public class TitleChanger extends JFrame implements ActionListener {
6: JButton b1 = new JButton(“Rosencrantz”);
7: JButton b2 = new JButton(“Guildenstern”);
8:
9: public TitleChanger() {
10: super(“Title Bar”);
11: setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
12: b1.addActionListener(this);
13: b2.addActionListener(this);
14: FlowLayout flow = new FlowLayout();
15: setLayout(flow);
16: add(b1);
17: add(b2);
18: pack();
19: setVisible(true);
20: }
21:
12
Search WWH ::




Custom Search