Java Reference
In-Depth Information
15.1 Introduction
You can write code to process events such as a button click, mouse movement, and
keystrokes.
Key
Point
Suppose you wish to write a GUI program that lets the user enter a loan amount, annual interest
rate, and number of years and click the Calculate button to obtain the monthly payment and
total payment, as shown in Figure 15.1. 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
F IGURE 15.1
The program computes loan payments.
Before delving into event-driven programming, it is helpful to get a taste using a simple
example. The example displays two buttons in a pane, as shown in Figure 15.2.
problem
(a)
(b)
F IGURE 15.2
(a) The program displays two buttons. (b) A message is displayed in the
console 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 cre-
ate an object capable of handling the action event on a button. This object is called an event
handler , as shown in Figure 15.3.
button
event
handler
Clicking a button
fires an action event
An event is
an object
The event handler
processes the event
(Event source object)
(Event object)
(Event handler object)
F IGURE 15.3
An event handler processes the event fired from the source object.
Not all objects can be handlers for an action event. To be a handler of an action event, two
requirements must be met:
1. The object must be an instance of the EventHandler<T extends Event> interface.
This interface defines the common behavior for all handlers. <T extends Event>
denotes that T is a generic type that is a subtype of Event .
EventHandler interface
2. The EventHandler object handler must be registered with the event source object
using the method source.setOnAction(handler) .
setOnAction(handler)
 
 
Search WWH ::




Custom Search