Introduction to the AWT Event Model

In the new event model, 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. Sometimes this model is called delegation, since it allows the programmer to delegate authority for event handling to any object that implements the appropriate listener interface. The new AWT event model lets you both handle and generate AWT events.

Event handlers can be instances of any class. As long as a class implements an event listener interface, its instances can handle events. In every program that has an event handler, you'll see three bits of code:

  1. In the class statement of the event handler, code declaring that the class implements a listener interface (or extends a class that implements a listener interface). For example:
  2. public class MyClass implements ActionListener {
         
  3. Code that registers an instance of the event handling class as a listener upon one or more components. For example:
  4. someComponent.addActionListener(instanceOfMyClass);
         
  5. The implementation of the methods in the listener interface. For example:
  6. public void actionPerformed(ActionEvent e) {
        ...//code that reacts to the action...
    }
         

A Simple Example

Here is a simple applet that illustrates event handling. It contains a single button that beeps when you click it.

</COMMENT> Since you can't run the applet, here's a picture of it: <BR> <IMG SRC="Beeper.gif" HEIGHT=107 WIDTH=257>

You can find the source in Beeper.java.

// beeper.java
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class Beeper extends JApplet 
                    implements ActionListener {
    JButton button;

    public void init() {
		Container c = getContentPane();
		c.setLayout(new FlowLayout());
        button = new JButton("Click Me");
		c.add(button);

        button.addActionListener(this);
    }

    public void actionPerformed(ActionEvent e) {
        Toolkit.getDefaultToolkit().beep();
    }
}

The Beeper class implements the ActionListener interface, which contains one method: actionPerformed. Since Beeper implements ActionListener, a Beeper object can register as a listener for the action events that buttons generate. Once the beeper has been registered using the button's addActionListener method, the beeper's actionPerformed method is called every time the button is clicked.