Java Reference
In-Depth Information
16.1 Introduction
You can write code to process events such as a button click or a timer.
Key
Point
Suppose you want to write a GUI program that lets the user enter a loan amount, annual inter-
est rate, and number of years and click the Compute Payment button to obtain the monthly pay-
ment and total payment, as shown in Figure 16.1a. How do you accomplish the task? You have
to use event-driven programming to write the code to respond to the button-clicking event.
problem
(a)
(b)
(c)
(d)
F IGURE 16.1
(a) The program computes loan payments. (b)-(d) A flag is rising upward.
Suppose you want to write a program that animates a rising flag, as shown in Figure 16.1b-d.
How do you accomplish the task? There are several ways to program this. An effective one is to
use a timer in event-driven programming, which is the subject of this chapter.
Before delving into event-driven programming, it is helpful to get a taste using a simple
example. The example displays two buttons in a frame, as shown in Figure 16.2.
problem
(a) (b)
F IGURE 16.2 (a) The program displays two buttons. (b) A message is displayed in the con-
sole when a button is clicked.
To respond to a button click, you need to write the code to process the button-clicking
action. The button is an event source object —where the action originates. You need to create
an object capable of handling the action event on a button. This object is called an event
listener , as shown in Figure 16.3.
button
event
listener
Clicking a button
fires an action event
An event is
an object
The listener object
processes the event
(Event source object)
(Event object)
(Event listener object)
F IGURE 16.3
A listener object processes the event fired from the source object.
Not all objects can be listeners for an action event. To be a listener of an action event, two
requirements must be met:
1. The object must be an instance of the ActionListener interface. This interface
defines the common behavior for all action listeners.
ActionListener interface
2. The ActionListener object listener must be registered with the event source
object using the method source.addActionListener(listener) .
addActionListener
(listener)
 
 
Search WWH ::




Custom Search