Delegation Event Model in Java
The Delegation Event Model is a design pattern used in Java to handle events like button clicks, key
presses, etc.
It is commonly used in GUI programming with AWT and Swing.
Components of the Delegation Event Model:
1. Event Source:
- The component that generates an event (e.g., Button, TextField).
2. Event Object:
- Contains information about the event.
- Subclasses of java.util.EventObject (e.g., ActionEvent, MouseEvent).
3. Event Listener:
- An interface that handles events.
- Implemented by classes that want to handle specific events (e.g., ActionListener,
MouseListener).
Working of the Model:
1. Register the listener with the source using methods like addActionListener().
2. When the event occurs, the source sends the event object to the listener.
3. The listener processes the event via a method like actionPerformed().
Example:
Button b = new Button("Click Me");
b.addActionListener(new MyActionListener());
class MyActionListener implements ActionListener {
public void actionPerformed(ActionEvent e) {
System.out.println("Button clicked!");
Advantages:
- Promotes loose coupling between event source and handler.
- More flexible and efficient event handling.
- Easier to reuse and organize code.