Java Reference
In-Depth Information
I ' m going to concentrate on the kinds of events that occur when a user interacts with a pro-
gram through its GUI.
THE EVENT-HANDLING PROCESS
To manage the user's interaction with the components that make up the GUI for a program, you must under-
stand how events are handled in Java. To get an idea of how this works, let's consider a specific example.
Don't worry too much about the class names and other details here. Just try to get a feel for how things con-
nect.
Suppose the user clicks a button in the GUI for your program. The button is the source of this event. The
event that is generated as a result of the mouse click is associated with the JButton object in your program
that represents the button on the screen. An event always has a source object — in this case the JButton
object. When the button is clicked, it creates a new object that represents and identifies this event — in this
case an object of type ActionEvent . This object contains information about the event and its source. Any
event that is passed to a Java program is represented by a particular event object — and this object is passed
as an argument to the method that is to handle the event. Figure 18-2 illustrates this mechanism.
FIGURE 18-2
The event object corresponding to the button click is passed to any listener object that has previously re-
gistered an interest in this kind of event — a listener object being simply an object that listens for particular
events. A listener is also called a target for an event. Here, “passing the event to the listener" just means the
object that is the event source calls a particular method in the listener object and passes the event object to
it as an argument. A listener object can listen for events for a particular object — just a single button, for
example — or it can listen for events for several different objects — a group of menu items, for example.
Which approach you take when you define a class representing listeners depends on the context and which
is most convenient from a programming point of view. Your programs often involve both.
 
 
Search WWH ::




Custom Search