Do you think IIT Guwahati certified course can help you in your career?
No
Introduction
In Java, event handling is crucial for developing interactive applications, especially in GUI programming. The Delegation Event Model is a powerful mechanism that enables efficient event-driven programming. It follows a producer-consumer approach, where an event source generates events, and listeners handle them. This model improves code organization, enhances reusability, and simplifies event processing. In this blog, we will explore the Delegation Event Model.
What is the delegation event model in Java?
The Delegation Event Model in Java is a mechanism for handling events in a structured way. It follows a producer-consumer approach, where an event source (e.g., a button) generates an event, and a listener (an object implementing a specific interface) processes it. This model improves event management by separating event generation from handling, making the code more modular and efficient. It is widely used in Swing, AWT, and JavaFX for GUI event handling.
For Example: For KeyEvent we use addKeyListener() to register, For ActionEvent we use addActionListener() to register.
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 the 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.
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.
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 the 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 is Delegation in Java?
Delegation in Java is a design principle where one object transfers responsibilities to another, improving modularity, reusability, and maintainability in event handling and design patterns.
What are the Benefits of the Delegation Event Model?
The Delegation Event Model improves code separation, reusability, and efficiency by decoupling event sources from listeners, enhancing maintainability and scalability in Java applications.
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.