5. Handling Events

5.1. Definition

When the user acts on a Component -- clicking it or pressing the Return key, for example -- an Event is generated.

5.2. Processing

  • Events are generated by event sources.

  • One or more listeners can register to be notified about events of a particular kind from a particular source.

  • Event handlers can be instances of any class. As long as a class implements an event listener interface.

5.3. To implement event handlers

  1. Code declaring that the class implements a listener interface:

    public class MyClass implements ActionListener {
  2. Code that registers an instance of the event handling class as a listener:

    someComponent.addActionListener(instanceOfMyClass);
  3. The implementation of the methods in the listener interface:

    public void actionPerformed(ActionEvent e) {
         ...//code that reacts to the action...
    }
[Note]Note

The AWT doesn't see every event that occurs. The AWT can see only those events that the platform-dependent code lets it see.

5.4. Handling Standard AWT Events

Table 10.1. AWT Events

Listener InterfaceAdapter ClassMethods
ActionListenernoneactionPerformed
AdjustmentListenernoneadjustmentValueChanged
ComponentListenerComponentAdaptercomponentHidden componentMoved componentResized componentShown
ContainerListenerContainerAdaptercomponentAdded componentRemoved
FocusListenerFocusAdapterfocusGained focusLost
ItemListenernoneitemStateChanged
KeyListenerKeyAdapterkeyPressed keyReleased keyTyped
MouseListenerMouseAdaptermouseClicked mouseEntered mouseExited mousePressed mouseReleased
MouseMotionListenerMouseMotionAdaptermouseDragged mouseMoved
TextListenernonetextValueChanged
WindowListenerWindowAdapterwindowActivated windowClosed windowClosing windowDeactivated windowDeiconified windowIconified windowOpened

5.5. AWT events are divided in 2 groups

5.5.1. Low-level events

They represent window-system occurrences or low-level input:

mouse and key events -- both of which result directly from user input .

5.5.2. Semantic events

These events are the result of component-specific user interaction:

A button generates an action event when the user clicks it.

5.6. Using Adapters to Handle Events

Most AWT listener interfaces contain more than one method.

For example, the MouseListener interface:

  1. mousePressed

  2. mouseReleased

  3. mouseEntered

  4. mouseExited

  5. mouseClicked

The AWT provides an adapter class for each listener interface with more than one method. For example, the MouseAdapter class implements the MouseListener interface.

An adapter class implements empty versions of all its interface's methods:

/*
 * An example of extending an adapter class instead of
 * directly implementing a listener interface.
 */
public class MyClass extends MouseAdapter {
    ... 
        someObject.addMouseListener(this);
    ... 
    public void mouseClicked(MouseEvent e) {
        ...//Event handler implementation goes here...
    }
}