Java Reference
In-Depth Information
The
ActionListener
interface contains the
actionPerformed
method for processing the
event. Your listener class must override this method to respond to the event. Listing 16.1 gives
the code that processes the
ActionEvent
on the two buttons. When you click the
OK
button,
the message “OK button clicked” is displayed. When you click the
Cancel
button, the mes-
sage “Cancel button clicked” is displayed, as shown in Figure 16.2.
L
ISTING
16.1
HandleEvent.java
1
import
javax.swing.*;
2
import
java.awt.event.*;
3
4
public class
HandleEvent
extends
JFrame
{
5
public
HandleEvent() {
6
// Create two buttons
7 JButton jbtOK =
new
JButton(
"OK"
);
8 JButton jbtCancel =
new
JButton(
"Cancel"
);
9
10
// Create a panel to hold buttons
11 JPanel panel =
new
JPanel();
12 panel.add(jbtOK);
13 panel.add(jbtCancel);
14
15 add(panel);
// Add panel to the frame
16
17
// Register listeners
18
19 CancelListenerClass listener2 =
new
CancelListenerClass();
20
21 jbtCancel.addActionListener(listener2);
22 }
23
24
OKListenerClass listener1 =
new
OKListenerClass();
create listener
jbtOK.addActionListener(listener1);
register listener
public static void
main(String[] args) {
25
26 frame.setTitle(
"Handle Event"
);
27 frame.setSize(
200
,
150
);
28 frame.setLocation(
200
,
100
);
29 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
30 frame.setVisible(
true
);
31 }
32 }
33
34
class
JFrame frame =
new
HandleEvent();
OKListenerClass
implements
ActionListener
{
listener
class
35 @Override
36
public void
actionPerformed(ActionEvent e) {
37 System.out.println
(
"OK button clicked"
);
38 }
39 }
40
41
class
process event
CancelListenerClass
implements
ActionListener
{
listener
class
42 @Override
43
public void
actionPerformed(ActionEvent e) {
44 System.out.println(
"Cancel button clicked"
);
45 }
46 }
process event
Two listener classes are defined in lines 34-46. Each listener class implements
ActionListener
to process
ActionEvent
. The object
listener1
is an instance of
OKListenerClass
(line 18), which is registered with the button
jbtOK
(line 20). When the
OK
button is clicked, the
actionPerformed(ActionEvent)
method (line 36) in