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 EventObjects as such; they work with subclasses that provide more specific information.

AWTEvent is a subclass of java.awt.EventObject; further subclasses of AWTEvent provide information about specific event types. Swing has events of its own that descend directly from EventObject. For 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 x and y coordinates and the state of your mouse buttons at the time the MouseEvent was created.

ActionEvent operates at a higher semantic level than MouseEvent: an 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.

Event Receivers and Listener Interfaces

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 actionPerformed() in the receiver:

    public void actionPerformed( ActionEvent e ) {

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 ActionEvents must implement the ActionListener interface:

    public interface ActionListener extends
    java.util.EventListener {
        public void actionPerformed( ActionEvent e );

All listener interfaces are subinterfaces of java.util.EventListener, which is an empty interface. It exists only to help Java-based tools such as IDEs identify listener interfaces.

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 FocusListener interface contains two methods:

    abstract void focusGained( FocusEvent e );
    abstract void focusLost( FocusEvent e );

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 AWTEvents contain a constant specifying the event’s type. But by using two methods, the FocusListener interface saves you the effort: if focusGained() is called, you know the event type was FOCUS_GAINED.

Similarly, the MouseListener interface defines five methods for receiving mouse events (and MouseMotionListener 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 object.

There can be more than one listener interface for dealing with a particular kind of event. For example, the MouseListener interface describes methods for receiving MouseEvents 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 void and take a single event object (a subclass of java.util.EventObject) as an argument.[39]

  • Listener interfaces are subclasses of java.util.EventListener that are named with the suffix “Listener”—for example, MouseListener and ActionListener.

These may seem obvious, but they are nonetheless important because they are our first hint of a design pattern governing how to build components that work with events.

Event Sources

The previous section described the machinery an event receiver uses to listen for events. In this section, we’ll describe how a receiver tells an event source to send it events as they occur.

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 Swing JButton class is a source of ActionEvents. Here’s how a TheReceiver object might register to receive these events:

    // receiver of ActionEvents
    class TheReceiver implements ActionListener
       // source of ActionEvents
       JButton theButton = new JButton("Belly");

       TheReceiver() {
          theButton.addActionListener( this );

       public void actionPerformed( ActionEvent e ) {
          // Belly Button pushed...

TheReciever makes a call to the button’s addActionListener() to receive ActionEvents from the button when they occur. It passes the reference this to register itself as an ActionListener.

To manage its listeners, an ActionEvent source (like the JButton) always implements two methods:

    // ActionEvent source
    public void addActionListener(ActionListener listener) {
    public void removeActionListener(ActionListener listener) {

The removeActionListener() 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 garbage-collected.

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 addActionListener() and 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 the FooListener interface must implement a pair of add/remove methods:

  • addFooListener(FooListener listener )

  • removeFooListener(FooListener listener )

If an event source can support only one event listener (unicast delivery), the add listener method can throw the java.util.TooManyListenersException.

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 ItemEvents from a JButton because a button doesn’t have an addItemListener() method. Java knows at compile time what types of events can be delivered to whom.

Event Delivery

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).

Event delivery

Figure 16-3. Event delivery

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.

Event Types

All the events used by Swing GUI components are subclasses of java.util.EventObject. 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 packages: java.awt.event and javax.swing.event. As 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 javax.swing.event.

java.awt.event.ComponentEvent 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.

The java.awt.event.InputEvent Class

MouseEvents, which 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.

Mouse and Key Modifiers on InputEvents

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 in java.awt.event.InputEvent:


Shift key with event


Control key with event


Windows Alt key or Mac Option/Alt with event; equivalent to BUTTON2_MASK


Mac Command key with event; equivalent to BUTTON3_MASK


Mouse Button 1


Mouse Button 2; equivalent to ALT_MASK


Mouse Button 3; equivalent to META_MASK

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 InputEvent’s getModifiers() method:

    public void mousePressed (MouseEvent e) {
        int mods = e.getModifiers();
        if ((mods & InputEvent.SHIFT_MASK) != 0) {
            // shifted Mouse Button press

The three BUTTON flags can determine which mouse button was pressed on a two- or three-button mouse. BUTTON2_MASK is equivalent to ALT_MASK, and 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).

Mouse-wheel events

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 ScrollPanes to operate as expected.

If you wish to explicitly handle mouse-wheel events, you can register to receive them using the MouseWheelListener 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 getWheelRotation() method, which returns a number of clicks.

Focus Events

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 JComponent 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 requestFocus() or requestFocusInWindow() methods. The requestFocusInWindow() method acts just like requestFocus() 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 FocusListener interface (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, JTextFields and 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 WindowEvents 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 FocusEventgetOppositeComponent() and WindowEvent getOppositeWindow() methods. If the opposite is part of a native non-Java application, then these values may be null.

Focus gained and lost events may also be marked as “temporary,” as determined by the FocusEvent 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.

[39] This rule is not complete. The JavaBeans conventions (see Chapter 22) allows event handler methods to take additional arguments when absolutely necessary and also to throw checked exceptions.

Get Learning Java, 4th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.