In this article, we will discuss the Delegation Event Model in Java. In Delegation Event Model in Java, let's first discuss what you mean by Event Model.
The Event model is based on two things, i.e., Event Source and Event Listeners.
Event Source means any object which creates the message or event.
Event Listeners are the object which receives the message or event.
Now, coming to the Delegation Event Model in Java, the Delegation event model is based upon Event Source, Event Listeners, and Event Objects.
Event Source is the class used to broadcast the events.
Event Listeners are the classes that receive notifications of events.
Event Object is the class object which describes the event.
Let's discuss how to implement the Delegation Event Model in Java.
What is delegation event model in Java?
Before discussing the Delegation Event Model in Java, let's discuss the Event Processing in Java.
In the Delegation model, a source generates an event and forwards it to one or more listeners, where the listener waits until they receive an event. Once the listener gets the event, it is processed by the listener, and then they return it. The UI elements can delegate an event's processing to a separate function.
This approach is more convenient than the event model (Java 1.0) because the events will only be received by the listeners who want to receive them in the delegation event model.
The essential advantage of the Delegation Event Model is that the application logic is completely separated from the interface logic.
Registering the Source With Listener in Delegation Event Model
The different Classes provide different registration methods.
For Example: For KeyEvent we use addKeyListener() to register, For ActionEvent we use addActionListener() to register.
Let's discuss some design goals of the event delegation model.
Event Processing in Java
Java supports event processing and supports the API used to develop the Desktop application, i.e., Abstract Window Toolkit.
Let's understand it graphically.
The delegation Model is the modern event processing approach, which has been available in Java since Java 1.1. It defines a standard and convenient mechanism to generate and process events.
Event Model includes the following three components:
Events
Events Sources
Events Listeners
1. Events
An event refers to an action that occurs within a graphical user interface (GUI), such as a button click, a key press, or a mouse movement. When an event is triggered, it is typically handled by an event listener or handler, which is registered to the graphical component that generates the event.
2. Event Sources
An event source is an object that generates an event. It is typically a graphical user interface (GUI) component, such as a button, a text field, or a menu item, but it can also be other types of objects that generate events, such as timers or sockets.
When an event is triggered on an event source, the event is encapsulated in an event object and passed to all the registered event listeners or handlers. The event source is responsible for notifying the event listeners or handlers of the event and providing them with the information they need to handle the event.
3. Event Listeners
An event listener is an object that is registered to an event source and is responsible for handling events that are generated by that source. When an event occurs on the event source, the event listener is notified and performs the necessary actions to respond to the event.
An event listener in Java is typically implemented as a class that implements a specific event listener interface, such as ActionListener, MouseListener, or KeyListener. Each interface specifies a set of methods that the event listener must implement to handle the corresponding type of event. For example, the ActionListener interface requires the implementation of a single method called actionPerformed, which is called when an action event occurs on the event source.
Types of Events
There are several types of events in the delegation event model, each with its own corresponding listener interfaces and methods for handling the events. Some common types of events in Java are:
1. The Foreground Events:
Foreground events typically refer to events that require immediate attention and are directly related to the user interaction or user interface. These events are important for the applications functioning and generally require user input or trigger visible changes in the interface of the application. Examples of foreground events include mouse movements, key presses, or button clicks.
2. The Background Events :
Background events occur in the background or behind the scenes, usually without requiring direct user interaction. These events may include tasks like network communication, data processing, or automated system operations. Background events are typically handled independently of the user interface. They may not have immediate visible effects but play a significant role in the overall functionality of an application.
What is Delegation Model?
The delegation model is a programming design pattern that is used to handle events and event-driven programming in graphical user interfaces (GUIs). The delegation model works by separating the concerns of event generation and event handling, allowing for greater modularity and flexibility in GUI programming.
In the delegation model, the objects responsible for generating events, such as buttons or menu items, are referred to as event sources. When an event occurs on an event source, the source creates an event object that encapsulates information about the event, such as its type and any associated data.
The delegation model has several advantages over other event-handling models. It allows for greater modularity and flexibility in GUI programming, as the event generation and event handling are separated into distinct objects. This makes it easier to change the behaviour of a GUI component without affecting other parts of the program.
Additionally, the delegation model supports multiple event listeners for a single event source, allowing for greater customization and flexibility in handling events. Overall, the delegation model is a powerful and flexible approach to handling events in GUI programming.
Delegation Event model
It has Sources and Listeners.
Source: Event sources are objects that generate events. They are responsible for detecting specific occurrences or changes in the application and notifying interested listeners about these events. An event source could be a GUI component like a button, text field, or menu item, or it could be any object that generates events based on user interactions or other application-specific triggers.
Listeners: Event listeners are objects that "listen" to specific events generated by event sources. When an event occurs, the corresponding listener's method(s) are invoked to handle that event.
Registering the Source With Listener
Registering the source with a listener is a crucial step in the Java Delegation Event Model. It establishes a connection between an event source and a listener, allowing the listener to receive and handle events generated by the source.
The following are the steps for registering the source with a listener:-
Create the Event Listener: Define a class that implements the appropriate listener interface for the type of event you want to handle. For example, if you're dealing with GUI events, you might implement the ActionListener interface.
Implement Listener Methods: Implement the methods specified by the listener interface within the listener class. These methods will be called when the associated event occurs.
Create the Event Source: Instantiate the event source object. This could be a GUI component like a button, text field, or menu item, depending on the type of event you're handling.
Instantiate the Listener: Create an instance of the listener class you implemented in step 1.
Register the Listener with the Event Source: Use a method provided by the event source to register the listener. This method varies depending on the event source and the type of event you're handling.
In the next section, you will learn about the different event classes in Java.
Event Classes in Java
The following are some commonly used event classes in Java:-
Event Class
Listener Interface
Description
ActionEvent
ActionListener
Represents an action, such as a button click, triggered by a GUI component.
MouseEvent
MouseListener
Represents mouse events like clicks, enters, exits, and button presses on a GUI component.
KeyEvent
KeyListener
Represents keyboard events, such as key presses and releases, from a GUI component.
WindowEvent
WindowListener
Represents window-related events, like opening, closing, or resizing a GUI window.
FocusEvent
FocusListener
Represents focus-related events, including gaining and losing focus on a GUI component.
In the following section, we will look at a Java program that implements the event delegation model.
Java Program to Implement the Event Delegation Model
import java.awt.*;
import java.awt.event.*;
public class TestApp {
public void search() {
System.out.println("Searching...");
}
public void sort() {
System.out.println("Sorting....");
}
public void delete(){
System.out.println("Deleting....");
}
static public void main(String args[]) {
TestApp app = new TestApp();
GUI gui = new GUI(app);
}
}
class Command implements ActionListener {
static final int SEARCH = 0;
static final int SORT = 1;
static final int DELETE =2;
int id;
TestApp app;
public Command(int id, TestApp app) {
this.id = id;
this.app = app;
}
public void actionPerformed(ActionEvent e) {
switch(id) {
case SEARCH:
app.search();
break;
case SORT:
app.sort();
break;
case DELETE:
app.delete();
}
}
}
class GUI {
public GUI(TestApp app) {
Frame f = new Frame();
f.setLayout(new FlowLayout());
Command searchCmd = new Command(Command.SEARCH, app);
Command sortCmd = new Command(Command.SORT, app);
Command deleteCmd = new Command(Command.DELETE, app);
Button b;
f.add(b = new Button("Search"));
b.addActionListener(searchCmd);
f.add(b = new Button("Sort"));
b.addActionListener(sortCmd);
f.add(b = new Button("Delete"));
b.addActionListener(deleteCmd);
List l;
f.add(l = new List());
l.add("Coding Ninjas");
l.add("Coding Ninjas Studio");
l.addActionListener(sortCmd);
f.pack();
f.show();
}
}
Output
Frequently Asked Questions
What is the mechanism of delegation event model?
The delegation event model involves objects delegating tasks to other objects in an event-driven programming paradigm. It allows for flexible and modular code by separating responsibilities, with objects triggering events and delegates executing corresponding tasks.
Why is event delegation important?
Event delegation is important because it helps us handle events more efficiently, especially when dealing with many elements. Delegating event handling to a common "leader" element reduces the number of event listeners and improves performance and memory usage.
What is the purpose of delegation in Java?
In Java, delegation allows objects to assign tasks to other objects. This helps keep our code flexible and organized. By dividing responsibilities, we can reuse code, simplify complex systems, and ensure each object focuses on what it does best.
What are the benefits of event delegation?
Event delegation offers several benefits: it minimizes the number of event handlers needed in a program, leading to improved performance and simpler maintenance. By handling events at a higher level (like a parent element), it enables dynamic handling of events for elements that may not exist yet. Additionally, it reduces memory usage, since fewer event handlers are attached, and simplifies event management in complex applications with numerous interactive elements.
Conclusion
We have discussed the Delegation Event Model in Java, including its syntax and example. We have also covered event processing and some design goals of the event delegation model.
After reading about the Delegation Event Model in Java, are you not feeling excited to read/explore more articles on Data Structures and Algorithms? Don't worry; Coding Ninjas has you covered. See Java, Basics of Java, Java AWT, Java AWT Basics, and Spring Boot to learn.