Canceling an event

Finally, we want to stop the weather from changing. To do so, we will call the setCancelled method of the event. The method takes a Boolean value as a parameter. We want canceled to equal true. Therefore, we will use the setCancelled(true) code, which is as follows:

package com.codisimus.norain;

import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.weather.WeatherChangeEvent;
import org.bukkit.plugin.java.JavaPlugin;

public class NoRain extends JavaPlugin implements Listener {
  @Override
  public void onEnable() {
    getServer().getPluginManager().registerEvents(this, this);
  }

  @EventHandler (ignoreCancelled = true, priority =EventPriority.LOW)
  public void onWeatherChange(WeatherChangeEvent event) {
    event.setCancelled(true);
  }
}

This plugin will work as is. However, there is room for improvement. What if it is already raining in the server world? This plugin would prevent the rain from ever stopping. Let's add an if statement so that the WeatherChangeEvent class will only be canceled if the weather is starting. The event provides us with a method called toWeatherState, which returns a Boolean value. This method will return true or false, informing us about whether the weather is starting or stopping respectively. This is also made clear in the API documentation:

Canceling an event

If toWeatherState returns true, then it is starting to rain. This is the case where we want to cancel the event. Now, let's write the same thing in Java, as follows:

if (event.toWeatherState()) {
  event.setCancelled(true);
}

After adding this if statement, you should test your plugin. Before installing the plugin, log on to your server and use the /toggledownfall command to make it rain. Once it is raining, install your newly created plugin and reload the server. At this point, it will still be raining, but you will be able to stop the rain by issuing the /toggledownfall command again. If you cannot do so, then the if statement that you added may be incorrect; review it to find your mistake and test it again. Once you stop the rain, you can try to use the same command to start the rain again. As long as the code is correct, the rain should not start. If the rain does start, then verify that your event listener is being properly registered within the onEnable method. Also, verify that the server is enabling the correct version of the plugin, as explained in Chapter 4, Testing on the Spigot Server.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.240.142