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:
public class MyClass implements ActionListener {
someComponent.addActionListener(instanceOfMyClass);
public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }
Here is a simple applet that illustrates event handling. It contains a single button that beeps when you click it.
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.