his chapter examines an important aspect of Java: the event. Event handling is
fundamental to Java programming because it is integral to the creation of applets and
other types of GUI-based programs. As explained in Chapter 21, applets are event-driven
programs that use a graphical user interface to interact with the user. Furthermore, any program
that uses a graphical user interface, such as a Java application written for Windows, is event
driven. Thus, you cannot write these types of programs without a solid command of event
handling. Events are supported by a number of packages, including java.util, java.awt, and
Most events to which your program will respond are generated when the user interacts
with a GUI-based program. These are the types of events examined in this chapter. They are
passed to your program in a variety of ways, with the specific method dependent upon the
actual event. There are several types of events, including those generated by the mouse, the
keyboard, and various GUI controls, such as a push button, scroll bar, or check box.
This chapter begins with an overview of Java's event handling mechanism. It then examines
the main event classes and interfaces used by the AWT and develops several examples that
demonstrate the fundamentals of event processing. This chapter also explains how to use
adapter classes, inner classes, and anonymous inner classes to streamline event handling code. The
examples provided in the remainder of this topic make frequent use of these techniques.
NOTE This chapter focuses on events related to GUI-based programs. However, events are also
occasionally used for purposes not directly related to GUI-based programs. In all cases, the same
basic event handling techniques apply.
Two Event Handling Mechanisms
Before beginning our discussion of event handling, an important point must be made: The way
in which events are handled changed significantly between the original version of Java (1.0)
and modern versions of Java, beginning with version 1.1. The 1.0 method of event handling is
still supported, but it is not recommended for new programs. Also, many of the methods
that support the old 1.0 event model have been deprecated. The modern approach is the way
that events should be handled by all new programs and thus is the method employed by
programs in this topic.
Search WWH :