Getting Your Programs to Listen

Before you can receive user input in a Java program, you must learn how to teach an object to listen. Responding to user events in a Java program requires the use of one or more EventListener interfaces. Interfaces are special classes that enable a class of objects to inherit behavior it would not be able to use otherwise. Adding an EventListener interface requires two things right away. First, because the listening classes are part of the java.awt.event group of classes, you must make them available with the following statement:

import java.awt.event.*;

Second, the class must use the implements statement to declare that it supports one or more listening interfaces. The following statement creates a class that uses ActionListener, an interface for responding to button and menu clicks:

public class Graph implements ActionListener {

EventListener interfaces enable a component of a graphical user interface to generate user events. Without one of the listeners in place, a component cannot do anything that can be heard by other parts of a program. A program must include a listener interface for each type of component to which it wants to listen. To have the program respond to a mouse-click on a button or the Enter key being pressed in a text field, you must include the ActionListener interface. To respond to the use of a choice list or check boxes, you need the ItemListener interface to respond to the use of a choice list or check boxes. When you require more than one interface in the same class, separate their names with commas after the implements statement, as in this code:

public class Graph3D implements ActionListener, MouseListener {
 // ...