The Java Programming Language:
The Java Event Model
An event is a signal received by a program from the operating system as a result of some action taken by the user, or because something else has happened. Here are some examples:
More generally, an event is a state change at an instant in time (Winston). The word "event" also refers to an instance of the EventObject class, or a subclass of that class. Thus, such an instance describes a state change at a particular instant.
Another kind of event is associated with variable-value changes.
The delegation event model defines standard and consistent mechanisms to generate and process events:
Key to understanding how the Java event model works is understanding how "listener classes" are used. A listener class may be defined by:
You must make sure that any listener class has appropriately defined listener methods, and that an instance of the listener class has been registered with the source of the event for which it is listening. The built-in machinery then notifies the listener object when the source object generates an event of the type for which the listener object is listening.
Every event handler requires three pieces of code:
public class MyClass implements ActionListener {
someComponent.addActionListener(instanceOfMyClass);
public void actionPerformed(ActionEvent e) { ...//code that reacts to the action... }
Event handlers can be instances of any class. Often an event handler that has only a few lines of code is implemented using an anonymous inner class--an unnamed class defined inside of another class. Anonymous inner classes can be confusing at first, but once you're used to them, they make the code clearer by keeping the implementation of an event handler close to where the event handler is registered.