Skip to content
piitex edited this page Dec 28, 2024 · 4 revisions

Events and Listeners

Events are actions that can be handled by a listener. For example, if you click on an image the OverlayClickEvent is called which can be handled using a listener. Below is an example of this.

@Listener
public void onImageClick(OverlayClickEvent event) {
  Overlay overlay = event.getOverlay();
  if (overlay instanceof ImageOverlay imageOverlay) {
    if (imageOverlay.getFileName().contains("myimage.png")) {
        // Handle event...  
    }
  }  
}

Typically events are actions, like pressing a button or clicking. There are some that aren't action like SceneStartEvent and StoryStartEvent which happen automatically without user input.

Creating Custom Event

You can create custom events which can handle specific actions or functions for your game.

public class MyCustomEvent extends Event {
  private final String eventData;

  public MyCustomEvent(String eventData) {
    this.eventData = eventData;
  }
  
  public String getEventData() {
    return eventData;
  }

}

Handling Custom Event

To handle a custom event you will have to call the event. This all depends on what the event is and how it is designed to be handled. To call an event use RenJava.getEventHandler().callEvent().

public void foo() {
  MyCustomEvent event = new MyCustomEvent("event data");
  RenJava.getEventHandler().callEvent(event);
}
@Listener
public void onCustomEvent(MyCustomEvent event) {
  String data = event.getEventData();
  // Handle event...
}

Event Chains

Sometimes an action can cause an event chain where multiple events can be called at once. For example, clicking can cause the MouseClickEvent and the OverlayClickEvent to be called simultaneously. It is more prevalent when dealing with asynchronous event calls. To better handle events in a chain you can now access the getLinkedEvents() which will return all events that were chained.

When an event is chained it is split into parent and child event. The parent is the most generic event. The above example with MouseClickEvent and OverlayClickEvent the mouse event is the parent and the overlay is the child. Event chains were used to fix an issue when renaming saves inside the in-game menu. The below checks if the overlay event was in a chain and handled to not process the click event.

@Listener(priority = Priority.LOWEST)
public void onMouseClick(MouseClickEvent event) {

  if (event.isCancelled()) {
    return;
  }

  // Check if the overlay event was called and if so cancel this event.
  for (Event e : event.getLinkedEvents()) {
    if (e instanceof OverlayClickEvent overlayClickEvent) {
      if (!overlayClickEvent.isHandleMouseEvent()) {
         return;
      }
    }
  }
}