ActionListener Example
This ActionListener example enables a JButton to react to it being pressed. When user's interact with components, events can be generated. A program can be made aware of events happening by listening for them.
An ActionListener interface does the listening and can be programmed to respond to events appropriately.
If you run the program in the Introduction to Programming system you will see how the control flows when you press the JButton.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ActionListener Example
import java.awt.event.*;
import javax.swing.*;
class ActionListenerExample {
public static void main(String[] args) {
JFrame jframe = new JFrame();
JButton b = new JButton("target");
ActionListener al = new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.out.println("action performed");
}
};
b.addActionListener(al);
jframe.getContentPane().add(b);
jframe.pack();
jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
jframe.setVisible(true);
}
}
13-17 An ActionListener variable is assigned to.
On the righthand side of the assignment is a construction that provides the ActionListener, and which includes a method ActionListener.actionPerformed() which will be invoked when an action event happens.
This unusual form of syntax is used because the ActionListener, being an interface, cannot instantiate an object.
19 The ActionListener is added to the JButton.
Thus, when the JButton is pressed, an action event happens that causes the ActionListener to react.
This in turn causes the ActonListener.actionPerformed() method to be invoked.
