Repository navigation
Your first Listener
Setting up this API and creating your first main class, was only the tip of the iceberg
Now we'll get into creating your first listener...
The way you would normally create a listener has not changed, the way you would register it though has changed a bit
Lets get started!
To create a listener, create a class that implements from the Listener interface like this:
public class MyListener implements Listener {
...
}This class now acts as an event listener for all sorts of events that might take place on our server
But currently, there is not code inside our class, which handles said events
For example, to handle an event which fires when a block breaks, you would implement it this way:
public class MyListener implements Listener {
@EventHandler
public void onPlayerBlockBreak(@NotNull BlockBreakEvent e) { // <- THE NAME OF THIS METHOD CAN BE WHATEVER YOU WANT
e.getPlayer().sendMessage("You broke a block of type: " + e.getBlock().getType());
}
...
}Now that we have a listener that handles a BlockBreakEvent, we can go ahead and register it when our plugin enables...
To do this, we head on over back to our main class and register the listener we just created within our onPluginEnable() Method:
public class MyPlugin extends RPlugin {
@Override
public void onPluginEnable() {
getListenerManager().register(new MyListener()); // <- Singular listener registration
getListenerManager().registerAll("PACKAGE NAME OF MULTIPLE LISTENERS"); // <- Multiple listener registration
Bukkit.getPluginManager().registerEvents(this, new MyAwesomeListener()) // <- WORKS, BUT NOT RECOMMENDED!
}
@Override
public void onPluginDisable() {
...
}
}DONE!
Thats all we need to create and register a fully functioning listener!