What is an event and what are the models available for event handling

?– An event is an event object that describes a state of change in a source. In other words, event occurs when an action is generated, like pressing button, clicking mouse, selecting a list, etc. There are two types of models for handling events and they are: a) event-inheritance model and b) event-delegation model.

In Core Java, an event refers to a happening or occurrence within a program that may be of interest to the program’s execution. Examples of events include user actions like mouse clicks, keyboard inputs, or system-generated events like a timer expiration.

Event handling in Java involves responding to these events in a program. There are two main models for event handling in Java:

  1. Delegation Event Model (or Delegation Model): This is the original event-handling model in Java. In this model, an event source (e.g., a button) delegates the responsibility of handling the event to a separate object known as an event listener or event handler. The event listener is registered with the event source, and when the event occurs, the listener’s corresponding method is invoked.

    Example interfaces in this model include ActionListener for handling action events (e.g., button clicks) and MouseListener for handling mouse events.

    java
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // Handle button click event
    }
    });
  2. Event Object Model (or Event Model): This model is introduced in the JavaBeans component architecture. In this model, events are represented as objects. Event sources produce event objects, and event listeners implement interfaces specific to each type of event. The listener objects are registered with the event source, and when an event occurs, the corresponding method in the listener is invoked with the event object as a parameter.

    Example interfaces in this model include ActionListener and MouseListener as well, but the methods take an ActionEvent or MouseEvent object as a parameter.

    java
    button.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e) {
    // Handle button click event using the ActionEvent object
    }
    });

In summary, both the Delegation Event Model and the Event Object Model are used for event handling in Java, but the Delegation Event Model is more prevalent and widely used. The choice of which model to use depends on the specific requirements of the application and developer preferences.