Page 691 - Introduction to Programming with Java: A Problem Solving Approach
P. 691
16.9 Component Listeners
When the user interacts with a component (e.g., when the user clicks a button or presses Enter while in a text box), the component fires an event. If the component has a listener attached to it, the fired event is “heard” by the listener. Consequently, the listener handles the event by executing its actionPerformed method. In this section, you’ll learn how to make all that work by creating a listener and an associated actionPerformed method.
How to Implement a Listener
Below, we show the steps needed to implement a listener for a text box. These steps correspond to the num- bered callouts in Figures 16.5a and 16.5b:
1. Define a class with an implements ActionListener clause appended to the right of the class’s heading.Toseeanexample,lookatcallout1inFigure16.5b.Theimplements ActionListener clause means that the class is an implementation of the ActionListener interface. We discuss in- terfaces in the next subsection.
2. Include an actionPerformed event handler method in your listener’s class. Here’s a skeleton of an actionPerformed method inside a listener class:
private class Listener implements ActionListener
{
public void acAtiponaPegrformePd(DAcFtionEvnenht ae)ncer {
<do-something>
}
Even if your actionPerformed method doesn’t use the ActionEvent parameter (e, above), you still must include that parameter in the method heading to make your method conform to the require- ments of a listener.
}
To see an example of a complete actionPerformed method, look at callout 2 in Figure 16.5b. It refers to a listener class that’s named Listener. Listener is not a reserved word—it’s just a good descriptive name we picked for the listener class in the Greeting program.
3. Register your listener class. More specifically, that means adding your listener class to a text box com- ponent by calling the addActionListener method. Here’s the syntax:
<text-box-component>.addActionListener(new <listener-class>());
To see an example, look at callout 3 in Figure 16.5a.
The point of the registration process is so your text box can find a listener when an enter event is
fired. An enter event is fired whenever the user presses Enter from within the text box.
Registering a listener is like registering your car. When you register your car, nothing much hap- pens at that point. But later, when some event occurs, your car registration comes into play. What event would cause your car registration to be used? If you get caught speeding, the police can use your registration number as part of a traffic citation. If you get into a wreck, your insurance company can use
your registration number to raise your insurance rates.
16.9 Component Listeners 657