Delegation Event Model in Java: Key Concepts and Best Practices

If you are looking for a Delegation Event Model in Java. Then, you are in the right place. In this article, we will cover everything about this topic.

The Delegation Event Model is a pattern that allows each component to communicate with each other. The Delegation Event Model is used to manage events in GUI programming, where GUI stands for Graphical User Interface. It allows users to interact with the system through visual elements like buttons, windows, and menus.

GUI programming is naturally event driven. If the user performs any activity on the GUI, such as mouse movement, click, scroll, or key press, these activities will be considered as events. Each event triggers a specific code that performs a corresponding function, this process is knows as event handling. Let’s discuss different components of an event module.

 

What is the Delegation Event Model?

Java 1.0 has started supporting event processing. It also supports API used to develop the Desktop application, i.e., Abstract Windows Toolkit. AWT was based on inheritance since Java 1.0. To process any user events, like mouse click, scroll, etc., for a program, it has to override action() or handleEvent() method of GUI component subclass.

Delegation Event Model in Java

But, Delegation Event Model is a modern way to handle event processing. It allows a standard and reliable mechanism to process events. This model is based on two things, i.e., event source and event listeners. Source will generate an event, and listener will accept that event and process it. Listeners will wait for an event. UI elements can pass the task of handling an event to a separate function.

An event model is essentially built on these three main components:

  • Events
  • Events Sources
  • Events Listeners

 

Events

The event can be generated from application GUI elements where a user can generate an event as a reaction, such as a mouse click, mouse scroll, or a key press. When an event is triggered by an end user, it is handled by an event listener or handler. There are multiple events that may occur which may not relate to user interaction, such as a timer elapse event, system failures, or a task getting completed, etc.

 

Event Sources

An event source is anything that triggers an event, like a button click, typing in a text box, or selecting a menu option. While these are usually GUI components, they can also be things like timers or network connections.

When something happens (like a button being clicked), the event source creates an event object containing all the details about that action. This event is then sent to all the listeners or handlers that are set up to respond. The event source ensures these listeners get the information they need to take action.

Example:

public void addTypeListener (TypeListener e1)

Event Listeners

Event listener is an object that listens for events from an event source and responds to them. Once an event happens, the listener is notified and takes the necessary actions to handle it.

In Java, event listeners are usually implemented as classes that follow specific event listener interfaces, like ActionListener, MouseListener, or KeyListener. Each interface outlines the methods the listener must implement to handle certain types of events. For instance, if you are using the ActionListener interface, you need to define the actionPerformed method, which gets triggered whenever an action event occurs on the event source, such as a button click.

Also Read:

What is Dynamic Binding in Java?
Structure of Java Program
Magic Number Program in Java

Types of Events

There are many types of Events in the delegation event model. Following two common types of Events in Java are:

 

1. The Foreground Events:

Foreground Events are basically events that happen directly due to user interaction and require immediate attention. These events are essential for an application’s functionality as they often involve user input or cause visible changes in the user interface. This includes actions like mouse movements, key presses, or button clicks.

 

2. The Background Events:

Background Events are basically events where user interactions are not required and run in the background. These events may be tasks like time events, automation data processing, schedulers, etc. Background events may not be visible to the user immediately, but this plays a significant role in the overall functionality of an application.

 

What is Delegation Model?

The delegation model is a most common design pattern used in programming, especially for handling events in GUIs. It helps keep things organized by separating the job of generating events like button clicks, from the job of handling them. This separation makes the code more flexible and easier to manage.

In the delegation model, objects that trigger events, such as buttons or menu items are called event sources. When something happens like a button is clicked, the event source creates an event object that holds all the details about the event, like its type and any extra information.

One of the main benefits of the delegation model is that it makes your program more modular. Since event generation and handling are kept separate, you can change the behavior of one part of the program without messing with other parts. Plus, the model lets you have multiple event listeners for a single event source, giving you more control and flexibility in how events are handled. In short, the delegation model is a great way to handle events in GUIs because it keeps things neat and adaptable.

 

Java Program to Implement the Event Deligation Model

The following Java program demonstrates how to handle events using the delegation  event model:

import java.awt.*;
import java.awt.event.*;

public class Application {
    // Method to perform a search operation
    public void performSearch() {
        System.out.println("Performing search...");
    }

    // Method to perform a sorting operation
    public void performSort() {
        System.out.println("Performing sort...");
    }

    public static void main(String[] args) {
        Application appInstance = new Application();
        Interface guiInterface = new Interface(appInstance);
    }
}

class ActionHandler implements ActionListener {
    static final int SEARCH_ACTION = 0;
    static final int SORT_ACTION = 1;
    int actionType;
    Application appInstance;

    // Constructor to initialize ActionHandler with the action type and app instance
    public ActionHandler(int actionType, Application appInstance) {
        this.actionType = actionType;
        this.appInstance = appInstance;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        switch (actionType) {
            case SEARCH_ACTION:
                appInstance.performSearch();
                break;
            case SORT_ACTION:
                appInstance.performSort();
                break;
        }
    }
}

class Interface {
    // Constructor to create and display the GUI
    public Interface(Application appInstance) {
        Frame frame = new Frame("Application Interface");

        // Create a Panel to organize components
        Panel panel = new Panel();
        panel.setLayout(new FlowLayout());

        ActionHandler searchAction = new ActionHandler(ActionHandler.SEARCH_ACTION, appInstance);
        ActionHandler sortAction = new ActionHandler(ActionHandler.SORT_ACTION, appInstance);

        Button searchBtn = new Button("Search");
        searchBtn.addActionListener(searchAction);
        panel.add(searchBtn);

        Button sortBtn = new Button("Sort");
        sortBtn.addActionListener(sortAction);
        panel.add(sortBtn);

        List sortOptions = new List();
        sortOptions.add("Alphabetical");
        sortOptions.add("Chronological");
        sortOptions.addActionListener(sortAction);
        panel.add(sortOptions);

        // Add the panel to the frame
        frame.add(panel);

        // Set frame size and visibility
        frame.setSize(300, 200);
        frame.setVisible(true);

        // Close the application when the window is closed
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent we) {
                System.exit(0);
            }
        });
    }
}
 

Output

Delegation Event Model in Java

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top