The article takes you to learn the Java event mechanism

  • 2021-11-29 07:00:57
  • OfStack

Summary of core components of directory delegate event model

I believe that most of the friends who do Java development have learned or at least understood Java GUI programming, in which there are a large number of bindings between events and controls. When we need to click a button to achieve certain operations, we actually register a listener for this button control to reasonably handle click events. In addition, Spring Framework also has many places where event handling mechanisms are used, such as ApplicationContextEvent and its subclasses, which represent events such as starting, stopping, closing and refreshing containers. This article will introduce you to the event handling mechanism of Java, and will also use examples to illustrate how to trigger and handle a custom event gracefully.

Delegate event model

Java has defined the way events are fetched and handled in Standard 1 since 1.1, based on the delegated event model. Its idea is very simple. The event source initiates a specific event and sends it to one or more event listeners, while the listener waits until it receives the event, then processes the event and returns. It is also simple to implement:

Defining Events Implement a specific listener interface to receive specific types of events Implement code that registers (or deactivates) listeners as recipients of specific event types Trigger an event at the right time

Core component

In this event handling mechanism of Java, there are three core components:

Event event object that describes the change of phase. For example, the click of an action in GUI, the start and stop of a container in Spring Framework, and more things such as computer startup, shutdown, hibernation, cache expiration, WeChat official account attention, closing and so on. The event source can be any object, which has the ability to trigger events. 1. The listener is registered (or deactivated) in this object, and the event is usually triggered here. One source may generate multiple different types of events. Event listeners should be registered for different event types, and one or more listeners can be registered for each event type. Event Listener A class that implements a specific interface, which needs to implement specific processing methods for a specific event and must be registered to that specific event.

Then the question arises, how can we gracefully trigger and handle a custom event?

Custom Events

Customizing events in Java is very simple. Considering that there is a need to bind social accounts in various applications, let's take this as an example and simply print a record when binding or unbinding social accounts.

First, define an event object with the following code:


public class SocialEvent extends EventObject {
    private static final long serialVersionUID = -5473622737706032666L;
    public static final int WECHAT_BIND = 1;
    public static final int WECHAT_UNBIND = 2;
    public static final int WEIBO_BIND = 3;
    public static final int WEIBO_UNBIND = 4;
    private int socialType;
    public SocialEvent(Object source, int socialType) {
        super(source);
        this.socialType = socialType;
    }
    public int getSocialType() {
        return socialType;
    }
    public void setSocialType(int socialType) {
        this.socialType = socialType;
    }
}

The event class must be EventObject Gets or sets a subclass of. It is worth mentioning that event objects usually represent class 1 rather than an event, that is, it is reasonable to merge the concepts of class 1 events rather than an event.

Next, we implement a set of event processing logic, that is, an event listener:


public class SocialEventListener implements EventListener {
    public void onSocialChanged(SocialEvent event) {
        switch (event.getSocialType()) {
            case SocialEvent.WECHAT_BIND:
                System.out.println("Wechat bind.");
                break;
            case SocialEvent.WECHAT_UNBIND:
                System.out.println("Wechat unbind.");
                break;
            case SocialEvent.WEIBO_BIND:
                System.out.println("Weibo bind.");
                break;
            case SocialEvent.WEIBO_UNBIND:
                System.out.println("Weibo unbind.");
                break;
            default:
                System.out.println("Bad social type.");
                break;
        }
    }
}

In addition, we need one event source:


public class Social {
    private List<SocialEventListener> listeners;
    public void addListener(SocialEventListener listener) {
        if (listeners == null) {
            listeners = new ArrayList<>();
        }
        listeners.add(listener);
    }
    public void removeListener(SocialEventListener listener) {
        if (listeners != null) {
            listeners.remove(listener);
        }
    }
    public void emitEvent(SocialEvent event) {
        for (SocialEventListener listener : listeners) {
            listener.onSocialChanged(event);
        }
    }
    public List<SocialEventListener> getListeners() {
        return listeners;
    }
    public void setListeners(List<SocialEventListener> listeners) {
        this.listeners = listeners;
    }
}

Here, we define the specialized class Social as the event source, and in fact, the event triggering and registration logic can be implemented in any other class, such as the startup class.

By the way, in Java GUI programming, we usually only need to register event listeners for components, without considering the trigger logic of events, because their events are automatically triggered by the system.

Summarize

This article is here, I hope to give you help, but also hope that you can pay more attention to this site more content!


Related articles: