-
Notifications
You must be signed in to change notification settings - Fork 0
Event
This guide covers how to create and manage events within an application using the EventBus framework.
To create a new event, extend the Event class. This base class can be expanded with any number of fields and methods necessary for your event's functionality.
public class TestEvent extends Event {
private String testString;
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
}Implement the Cancellable interface in your event class to allow event cancellation. The Cancellable interface provides default methods for cancellation logic and immediate propagation stop, eliminating the need for explicit implementation.
public class TestEvent extends Event implements Cancellable {
private String testString;
public String getTestString() {
return testString;
}
public void setTestString(String testString) {
this.testString = testString;
}
}Note
Cancelling an event doesn't interfere with triggering of event handlers, however, it forbids the original intended action
On the other hand, stopping the event's immediate propagation does not prevent the original action from occurring, but it restricts the triggering of any subsequent event handlers, excluding the MONITOR priority.
Events can inherit from other events to create a hierarchy. This allows for more specific event types while still triggering handlers for the base event type.
public class DerivativeEvent extends TestEvent {
private boolean testBoolean;
public boolean isTestBoolean() {
return testBoolean;
}
public void setTestBoolean(boolean testBoolean) {
this.testBoolean = testBoolean;
}
}Note
Handlers for TestEvent will also trigger for DerivativeEvent unless explicitly configured not to.
To fire an event, obtain an instance of the EventBus, create an event instance, and use the fireEvent method. You can then inspect the event instance for results or status.
public static void main(String[] args) {
// Obtain the default EventBus instance
EventBus eventBus = EventBus.getDefault();
// Create and fire the event
TestEvent event = new TestEvent();
eventBus.fireEvent();
// Check the event's status
System.out.println("Cancelled: " + event.isCancelled());
System.out.println(event.getTestString());
}