7-event-handling
7-event-handling
➢ Any program that uses a graphical user interface, such as a Java application written for
Windows, is event driven.
➢ Events are supported by a number of packages, including java.util, java.awt, and
java.awt.event.
➢ 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.
The Delegation Event Model
➢ The modern approach to handling events is based on the delegation event model, which
defines standard and consistent mechanisms to generate and process events.
➢ A source generates an event and sends it to one or more listeners.
➢ The listener simply waits until it receives an event.
➢ Once an event is received, the listener processes the event and then returns.
➢ In the delegation event model, listeners must register with a source in order to receive an
event notification.
➢ This provides an important benefit: notifications are sent only to listeners that want to
receive them.
Events
➢ In the delegation model, an event is an object that describes a state change in a source.
➢ It can be generated as a consequence of a person interacting with the elements in a
graphical user interface.
➢ Some of the activities that cause events to be generated are pressing a button, entering a
character via the keyboard, selecting an item in a list, and clicking the mouse.
➢ Events may also occur that are not directly caused by interactions with a user interface.
➢ For example, an event may be generated when a timer expires, a counter exceeds a
value, a software or hardware failure occurs, or an operation is completed.
➢ You are free to define events that are appropriate for your application.
Event Sources
➢ A source is an object that generates an event.
➢ This occurs when the internal state of that object changes in some way.
➢ Sources may generate more than one type of event.
➢ A source must register listeners in order for the listeners to receive notifications about a
specific type of event.
➢ Each type of event has its own registration method. Here is the general form: