Search code examples
javaeventsbukkit

How to fire events using Bukkit API?


I was looking at how to create and fire events using Bukkit API.

public class PlayerDisconnect implements Listener {
    @EventHandler
    public void onQuit(PlayerQuitEvent event){
        //code
    }
}

I mean, doesn't matter the name of the method (in this case onQuit, I can use onDisconnect, onLeave, etc. and it will still be called by PlayerQuitEvent), it calls every method using PlayerQuitEvent as a parameter. I want to be able to replicate that behaviour.


Solution

  • You can create and call your own custom events using the Bukkit Event API. Spigot has a good starting tutorial on the Event API.

    A simple example of a Cancellable event that takes a Player:

    ...
    import org.bukkit.entity.Player;
    import org.bukkit.event.Cancellable;
    import org.bukkit.event.Event;
    import org.bukkit.event.HandlerList;
    
    public class MyCustomEvent extends Event implements Cancellable
    {
        private static final HandlerList handlers = new HandlerList();
    
        private final Player player;
        private boolean cancelled;
    
        public MyCustomEvent(Player player)
        {
            this.player = player;
        }
    
        public static HandlerList getHandlerList()
        {
            return handlers;
        }
    
        public Player getPlayer()
        {
            return this.player;
        }
    
        public HandlerList getHandlers()
        {
            return handlers;
        }
    
        @Override
        public boolean isCancelled() 
        {
            return cancelled;
        }
    
        @Override
        public void setCancelled(boolean cancelled) 
        {
            this.cancelled = cancelled;
        }
    
    }
    

    Which you can then call elsewhere in your custom event like so

    ...
    MyCustomEvent event = new MyCustomEvent(player);
    Bukkit.getPluginManager().callEvent(event);
    if (event.isCancelled())
        return;
    ...
    

    Finally, you would listen for the event like you would any other event:

    ...
    @EventHandler
    public void onMyCustomEvent(MyCustomEvent event){
        Player player = event.getPlayer();
        ...
    }