An event is actually an instruction. It could be generated by devices like a mouse or a keyboard or it could be generated when a timer stops or a system fails.
Java uses Delegation Event Model to handle the events. In this model, there are two separate objects, source and listeners. A source is used to generate the events. When a event is generated, the state of the object is changed. One source can generate many events. These events are then sent to listeners. A listener must be registered to the particular source to receive an event. Listeners keep waiting until they receive an event. After receiving the event a listener’s job is to execute the event. In the occasion of a new event, all registered users are notified and a copy of event object is send to them.
To receive events, interfaces and codes to register and unregister are implemented by listeners. Syntax to register a listener:
public void addTypeListener(TypeListener elr)
where, elr is event listener reference.
For Example, for a mouse event MouseListener, MouseMotionListener interfaces are implemented.
void addMouseListener(MouseListener mlr)
void addMouseMotionListener(MouseMotionListener mmlr)
where, mlr is mouse listener reference and mmlr is mouse motion listener reference.
To register a single listener:
public void addTypeListener(TypeListener elr) throws java.util.TooManyListenersException
To unregister a listener:
public void removeTypeListener(TypeListener elr)