Getting Your Programs to Listen

A user event in Java is something that happens when a user performs an action with the mouse, keyboard, or another input device.

Before you can receive events, you must learn how to make an object listen. Responding to user events requires the use of one or more EventListener interfaces. Interfaces are a feature of object-oriented programming in Java that enable a class to inherit behavior it would not be able to employ otherwise. They’re like a contract agreement with other classes that guarantee the class will contain specific methods.

An EventListener interface contains methods that receive user input of a specific type.

Adding an EventListener interface requires two things. First, because the listening classes are part of the java.awt.event package, you must make them available with the following statement:

import java.awt.event.*;

Second, the class must use the implements keyword 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 GUI 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 listens. 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.

When you require more than one interface in the same class, separate their names with commas after the implements keyword, as in this code:

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

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.237.201