Java Reference
In-Depth Information
17.1
Event-Driven Programming
My duty is to obey orders.
THOMAS JONATHAN (STONEWALL) JACKSON
Event-driven programming
is a programming style that uses a signal-and-response
approach to programming. Signals to objects are things called
event-driven
programming
events,
a concept we
explain in this section.
Events and Listeners
event
listener
firing an
event
Swing programs use events and event handlers. An
event
is an object that acts as a sig-
nal to another object known as a
listener
. The sending of the event is called
firing the
event
. The object that fires the event is often a GUI component, such as a button. The
button fires the event in response to being clicked. The listener object performs some
action in response to the event. For example, the listener might place a message on the
screen in response to a particular button being clicked. A given component may have
any number of listeners, from zero to several listeners. Each listener might respond to
a different kind of event, or multiple listeners might respond to the same events.
If you have read Chapter 9 on exception handling, then you have already seen one
specialized example of event-driven programming.
2
An exception object is an event.
The throwing of an exception is an example of firing an event (in this case firing the
exception event). The listener is the
block that catches the event.
In Swing GUIs an event often represents some action such as clicking a mouse,
dragging the mouse, pressing a key on the keyboard, clicking the close-window button
on a window, or any other action that is expected to elicit a response. A listener object
has methods that specify what will happen when events of various kinds are received
by the listener. These methods that handle events are called
catch
. You the
programmer will define (or redefine) these event-handler methods. The relationship
between an event-firing object, such as a button, and its event-handling listener is
shown diagrammatically in Display 17.1.
Event-driven programming is very different from most programming you've seen
before now. All our previous programs consisted of a list of statements executed in
order. There were loops that repeat statements and branches that choose one of a list of
statements to execute next. However, at some level, each run of a program consists of a
list of statements performed by one agent (the computer) that executes the statements
one after the other in order.
Event-driven programming is a very different game. In event-driven programming,
you create objects that can fire events, and you create listener objects to react to the
events. For the most part, your program does not determine the order in which things
happen. The events determine that order. When an event-driven program is running,
event handlers
event handler
2
If you have not yet covered Chapter 9 on exceptions, you can safely ignore this paragraph.
Search WWH ::




Custom Search