Java Reference
In-Depth Information
This sounds somewhat abstract, so let's run through an extremely simple program that
prints a message whenever a button is clicked. Button listeners must belong to a class
that implements the
ActionListener
interface:
public interface ActionListener
{
void actionPerformed(ActionEvent event);
}
This particular interface has a single method,
actionPerformed
. It is your job to
supply a class whose
actionPerformed
method contains the instructions that you
want executed whenever the button is clicked. Here is a very simple example of such
a listener class:
ch09/button1/ClickListener.java
1
import
java.awt.event.ActionEvent;
2
import
java.awt.event.ActionListener;
3
4 /**
5
An action listener that prints a message.
6 */
7
public class
ClickListener
implements
ActionListener
8 {
9
public void
actionPerformed(ActionEvent
event)
10 {
11 System.out.println(
"I was clicked."
);
12 }
13 }
We ignore the
event
parameter of the
actionPerformed
methodȌit contains
additional details about the event, such as the time at which it occurred.
Once the listener class has been defined, we need to construct an object of the class
and add it to the button:
ActionListener listener = new ClickListener();
button.addActionListener(listener);
Whenever the button is clicked, it calls