Page 692 - Introduction to Programming with Java: A Problem Solving Approach
P. 692
658 Chapter 16 GUI Programming Basics
4. Import the java.awt.event package. Event handling requires the use of the ActionListener interface and the ActionEvent class. Those entities are in the java.awt.event package, so that package must be imported for event handling to work. To see the import statements within a complete program, look at callout 4 in Figure 16.5a.
The ActionListener Interface
In the Greeting program, we specified implements ActionListener in the listener’s class heading. ActionListener is an interface. You might recall interfaces from Chapter 13. An interface is somewhat like a class in that it contains variables and methods. But unlike a class, its variables must be constants (i.e., final variables), and its methods must be empty (i.e., method headings). If a programmer uses an interface to derive a new class, the compiler requires the new class to implement methods for all of the interface’s method headings.
So what’s the point of having an interface with all empty methods? The answer is that it can be used as a template or pattern when creating a class that falls into a certain category. More specifically, what’s the point of the ActionListener interface? Since all action-event listeners must implement it, it means that all action-event listeners will be similar and therefore understandable. It means that all action-event listeners will implement the ActionListener’s one method, the actionPerformed method. And in implementing that method, they’ll be forced to use this prescribed heading:
public void actionPerformed(ActionEvent e)
By using the prescribed heading, it ensures that fired action events will be received properly by the listener.
Apago PDF Enhancer
16.10 Inner Classes
Here’s a reprint of the Greeting program, in skeleton form:
public class Greeting extends JFrame
{
}
// end class Greeting
...
private class Listener implements ActionListener
{
...
public void actionPerformed(ActionEvent e)
{
}
String message; // the personalized greeting
message = "Glad to meet you, " + nameBox.getText();
nameBox.setText("");
greeting.setText(message);
// end actionPerformed
} // end class Listener
Do you notice anything odd about the position of the Listener class in the Greeting program? See how the Listener class is indented and how its closing brace is before the Greeting class’s closing brace? The Listener class is inside of the Greeting class!