We’ve spent a lot of time discussing the different kinds of objects in Swing—components, containers, and special containers such as frames and windows. Now it’s time to discuss interobject communication in detail.
Swing objects communicate by sending events. The way we talk about events—“firing” them and “handling” them—makes it sound as if they are part of some special Java language feature. But they aren’t. An event is simply an ordinary Java object that is delivered to its receiver by invoking an ordinary Java method. Everything else, however interesting, is purely convention. The entire Java event mechanism is really just a set of conventions for the kinds of descriptive objects that should be delivered; these conventions prescribe when, how, and to whom events should be delivered.
Events are sent from a single source object to one or more listeners. A listener implements prescribed event-handling methods that enable it to receive a type of event. It then registers itself with a source of that kind of event. Sometimes an adapter object may be interposed between the event source and the listener, but in any case, registration of a listener is always established before any events are delivered.
An event object is an instance of a subclass of
java.util.EventObject; it holds information
about something that’s happened to its source. The
EventObject parent class itself serves mainly to
identify event objects; the only information it contains is a reference to
the event source (the object that sent the event). Components don’t
normally send or receive
as such; they work with subclasses that provide more specific
AWTEvent is a subclass
information about specific event types. Swing has events of its own that
descend directly from
the most part, you’ll just be working with specific event subclasses from
the AWT or Swing packages.
ActionEvents correspond to a
decisive “action” that a user has taken with the component, such as
clicking a button or pressing Enter. An
ActionEvent carries the
name of an action to be performed (the action
command) by the program.
MouseEvents are generated
when a user uses the mouse within a component’s area. They describe the
state of the mouse and therefore carry such information as the
coordinates and the state of your mouse buttons at the time the
MouseEvent was created.
ActionEvent operates at a higher
semantic level than
ActionEvent lets us know that a
component has performed its job; a
MouseEvent simply confers a lot of information
about the mouse at a given time. You could figure out that somebody
clicked on a
JButton by examining mouse
events, but it is simpler to work with action events. The precise meaning
of an event can also depend on the context in which it is received.
An event is delivered by passing it as an argument to the
receiving object’s event handler method.
ActionEvents, for example, are always
delivered to a method called
For each type of event, a corresponding listener interface
prescribes the method(s) it must provide to receive those events. In
this case, any object that receives
Events must implement the
Listener interfaces are required for a number of reasons. First,
they help to identify objects that can receive a given type of
event—they make event hookups “strongly typed.” Event listener interfaces allow us
to give the event handler methods friendly, descriptive names and still
make it easy for documentation, tools, and humans to recognize them in a
class. Next, listener interfaces are useful because several methods can
be specified for an event receiver. For example, the
contains two methods:
Although these methods each take a
FocusEvent as an
argument, they correspond to different reasons (contexts) for firing the
event—in this case, whether the
FocusEvent means that focus was received or
lost. In this case, you could also figure out what happened by
inspecting the event; all
contain a constant specifying the event’s type. But by using two
saves you the effort: if
focusGained() is called, you know the event
defines five methods for receiving mouse events (and
defines two more), each of which gives you some additional information
about why the event occurred. In general, the listener interfaces group
sets of related event handler methods; the method called in any given
situation provides a context for the information in the event
There can be more than one listener interface for dealing with a
particular kind of event. For example, the
MouseListener interface describes methods for
Events when the mouse enters or exits an
area or a mouse button is pressed or released.
MouseMotionListener is an entirely separate
interface that describes methods to get mouse events when the mouse is
moved (no buttons pressed) or dragged (buttons pressed). By separating
mouse events into these two categories, Java lets you be a little more
selective about the circumstances under which you want to receive
MouseEvents. You can register as a
listener for mouse events without receiving mouse motion events; because
mouse motion events are extremely common, you don’t want to handle them
if you don’t need to.
Two simple patterns govern the naming of Swing event listener interfaces and handler methods:
Event handler methods are public methods that return type
voidand take a single event object (a subclass of
java.util.EventObject) as an argument.
Listener interfaces are subclasses of
java.util.EventListenerthat are named with the suffix “Listener”—for example,
To receive events, an eligible listener must register itself with
an event source. It does this by calling an “add listener” method in the
event source and passing a reference to itself. (Thus, this scheme
implements a callback facility.) For example, the
JButton class is a source of
ActionEvents. Here’s how a
TheReceiver object might register to receive
// receiver of ActionEvents
// source of ActionEvents
// Belly Button pushed...
TheReciever makes a call to the
ActionEvents from the button
when they occur. It passes the reference
this to register itself as an
To manage its listeners, an
ActionEvent source (like the
JButton) always implements two methods:
// ActionEvent source
method removes the listener from the list so that it will not receive
future events of that kind. Swing components supply implementations of
both methods; normally, you won’t need to implement them yourself. It’s
important to pay attention to how your application uses event sources
and listeners. It’s OK to throw away an event source without removing
its listeners, but it isn’t necessarily OK to throw away listeners
without removing them from the source first because the event source
might maintain references to them, preventing them from being
You may be expecting some kind of “event source” interface listing
these two methods and identifying an object as a source of this event
type, but there isn’t one. There are no event source interfaces in the
current conventions. If you are analyzing a class and trying to
determine what events it generates, you have to look for the paired add
and remove methods. For example, the presence of the
removeActionListener() methods define
the object as a source of
ActionEvents. If you happen to be a human
being, you can simply look at the documentation, but if the
documentation isn’t available, or if you’re writing a program that needs
to analyze a class (a process called reflection),
you can look for this design pattern. (The
java.beans.Introspector utility class can do
this for you.)
A source of
FooEvent events for
FooListener interface must
implement a pair of add/remove methods:
What do all the naming patterns up to this point accomplish? For one thing, they make it possible for automated tools and integrated development environments to divine sources of particular events. Tools that work with JavaBeans will use the Java reflection and introspection APIs to search for these kinds of design patterns and identify the events that can be fired by a component.
At a more concrete level, it also means that event hookups are
strongly typed, just like the rest of Java. So it’s impossible to
accidentally hook up the wrong kind of components; for example, you
can’t register to receive
JButton because a button
doesn’t have an
method. Java knows at compile time what types of events can be delivered
Swing and AWT events are multicast; every event is associated with a single source but can be delivered to any number of receivers. When an event is fired, it is delivered individually to each listener on the list (see Figure 16-3).
There are no guarantees about the order in which events are delivered. Nor are there any guarantees about what happens if you register yourself more than once with an event source; you may or may not get the event more than once. Similarly, you should assume that every listener receives the same event data. In general, events are immutable; they can’t be changed by their listeners.
To be complete, we could say that event delivery is synchronous with respect to the event source, but that is because the event delivery is really just the invocation of a normal Java method. The source of the event calls the handler method of each listener. However, listeners shouldn’t assume that all the events will be sent in the same thread unless they are AWT/Swing events, which are always sent serially by a global event dispatcher thread.
All the events used by Swing GUI components are subclasses
You can use or subclass any of the
EventObject types for use in your own
components. We describe the important event types here.
The events and listeners that are used by Swing fall into two
we’ve discussed, the structure of components has changed significantly
between AWT and Swing. The event mechanism, however, is fundamentally
the same, so the events and listeners in
java.awt.event are used by Swing components.
In addition, Swing has added event types and listeners in the package
is the base class for events that can be fired by any component. This
includes events that provide notification when a component changes its
dimensions or visibility, as well as the other event types for mouse
operations and keypresses.
ContainerEvents are fired by containers when
components are added or removed.
track the state of the mouse, and
KeyEvents, which are fired when the user uses
the keyboard, are kinds of
java.awt.event.InputEvents. When the user
presses a key or moves the mouse within a component’s area, the events
are generated with that component identified as the source.
Input events and GUI events are processed in a special event queue that is managed by Swing. This gives Swing control over how all its events are delivered. First, under some circumstances, a sequence of the same type of event may be compressed into a single event. This is done to make some event types more efficient—in particular, mouse events and some special internal events used to control repainting. Perhaps more important to us, input events are delivered with extra information that lets listeners decide if the component itself should act on the event.
InputEvents come with
a set of flags for special modifiers. These let you detect whether the
Shift, Control, or Alt keys were held down during a mouse button or
keypress, and, in the case of a mouse button press, distinguish which
mouse button was involved. The following are the flag values contained
To check for one or more flags, evaluate the bitwise AND of the
complete set of modifiers and the flag or flags you’re interested in.
The complete set of modifiers involved in the event is returned by the
// shifted Mouse Button press
BUTTON flags can
determine which mouse button was pressed on a two- or three-button
BUTTON2_MASK is equivalent to
BUTTON3_MASK is equivalent to
META_MASK. This means that pushing the second
mouse button is equivalent to pressing the first (or only) button with
the Alt key depressed, and the third button is equivalent to the first
with the “Meta” key depressed. These provide some minimal portability
even for systems that don’t provide multibutton mice. However, for the
most common uses of these buttons—pop-up menus—you don’t have to write
explicit code; Swing provides special support that automatically maps to
the correct gesture in each environment (see the
PopupMenu class in Chapter 17).
Java 1.4 added support for the mouse wheel, which is a
scrolling device in place of a middle mouse button. By default, Swing
handles mouse-wheel movement for scrollable components, so you should
not have to write explicit code to handle this. Mouse-wheel events are
handled a little differently from other events because the conventions
for using the mouse wheel don’t always require the mouse to be over a
scrolling component. If the immediate target component of a
mouse-wheel event is not registered to receive it, a search is made
for the first enclosing container that wants to consume the event.
This allows components enclosed in
operate as expected.
If you wish to explicitly handle mouse-wheel events, you can
register to receive them using the
interface shown in Table 16-1 in the
next section. Mouse-wheel events encapsulate information about the
amount of scrolling and the type of scroll unit, which on most systems
may be configured externally to be fine-grained scroll units or large
blocks. If you want a physical measure of how far the wheel was
turned, you can get that with the
method, which returns a number of clicks.
As we mentioned earlier, focus handling is largely done automatically in Swing applications and we’ll discuss it further in Chapter 18. However, understanding how focus events are handled will help you understand and customize components.
As we described, a component can make itself eligible to receive
focus using the
setFocusable() method (Windows may use
setFocusableWindowState()). A component
normally receives focus when the user clicks on it with the mouse. It
can also programmatically request focus using the
method acts just like
except that it does not ask for transfer across windows. (There are
currently limitations on some platforms that prevent focus transfer from
native applications to Java applications, so using
requestFocusInWindow() guarantees portability
by adding this restriction.)
Although a component can request focus explicitly, the only way to
verify when a component has received or lost focus is by using the
(see Tables 16-1 and 16-2).
You can use this interface to customize the behavior of your component
when it is ready for input (e.g., the
TextField’s blinking cursor). Also, input
components often respond to the loss of focus by committing their
changes. For example,
other components can be arranged to validate themselves when the user
attempts to move to a new field and to prevent the focus change until
the field is valid (as we’ll see in Chapter 18).
Assuming that there is currently no focus, the following sequence of events happens when a component receives focus:
The first two are
delivered to the component’s containing
Window, and the third is a
FocusEvent that is sent to the component
itself. If a component in another window subsequently receives focus,
the following complementary sequence will occur:
These events carry a certain amount of context with them. The
receiving component can determine the component and window from which
the focus is being transferred. The yielding component and window are
called “opposites” and are available with the
methods. If the opposite is part of a native non-Java application, then
these values may be
Focus gained and lost events may also be marked as “temporary,” as
determined by the
isTemporary() method. The concept of a temporary focus change
is used for components such as pop-up menus, scrollbars, and window
manipulation where control is expected to return to the primary
component later. The distinction is made for components to “commit” or
validate data upon losing focus. No commit should happen on a temporary
loss of focus.