Java Reference
In-Depth Information
By default, if you don't specify how to react to an event, it goes unnoticed by your
program. Therefore, nothing happens when the user clicks your buttons or types in
your text fields. You can cause the program to respond to a particular event (such as
the user clicking a button) by using an object called a listener.
Listener
An object that is notified when an event occurs and that executes code to
respond to the event.
To handle an event, create a listener object and attach it to the component of inter-
est. The listener object contains the code that you want to run when the appropriate
event occurs.
The first kind of event we'll handle in this chapter is called an action event . An
action event is a fairly general type of event that occurs when the user interacts with
many standard components (for example, clicking on a button or entering text into a
JTextField ).
In Java, event listeners are written by implementing particular interfaces. The
interface for handling action events in Java is called ActionListener . The
ActionListener interface is located in the java.awt.event package, which you'll
need to import.
import java.awt.event.*; // for action events
Even if you've already imported the java.awt package, you'll still need to sepa-
rately import the java.awt.event package, because it is not contained within
java.awt .
The ActionListener interface contains only the following method:
public void actionPerformed(ActionEvent event)
To listen to an event, you write a class that implements the ActionListener
interface and place into its actionPerformed method the code that you want to run
when the event occurs. Then you attach an object of your listener class to the appro-
priate component.
Here is a simple example of an ActionListener class that responds to an event
by displaying a message box on the screen:
1 // Responds to a button click by displaying a message box.
2
3 import java.awt.event.*;
4 import javax.swing.*;
5
6 public class MessageListener implements ActionListener {
7 public void actionPerformed(ActionEvent event) {
 
Search WWH ::




Custom Search