How to register an event in coding a spigot plugin?

Viewed 590

I have tried randomizing potion effects every time a player eats something. I used this code, but nothing happened:

package de.jobebe.randomizer;

import java.util.concurrent.ThreadLocalRandom;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

public class Main extends JavaPlugin {
    
    @Override
    public void onEnable() {

    }
    
    @Override
    public void onDisable() {
    
    }

    @EventHandler
    public void onChowDown(PlayerItemConsumeEvent e) {
        int rnd = ThreadLocalRandom.current().nextInt(PotionEffectType.values().length);
        e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.values()[rnd], 200, 1));
    }
}

I researched a bit, but everything I found was that I have to register an event in the onEnable Method. But if I try this like that getServer().getPluginManager().registerEvents(this, this); it throws an error in Eclipse because the Method needs a Listener. Can I register this event differently?

1 Answers

You should make the method implements Listener, and so have like that :

package de.jobebe.randomizer;

import java.util.concurrent.ThreadLocalRandom;

import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerItemConsumeEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.potion.PotionEffect;
import org.bukkit.potion.PotionEffectType;

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

    @EventHandler
    public void onChowDown(PlayerItemConsumeEvent e) {
        int rnd = ThreadLocalRandom.current().nextInt(PotionEffectType.values().length);
        e.getPlayer().addPotionEffect(new PotionEffect(PotionEffectType.values()[rnd], 200, 1));
    }
}

Now, it will works fine.

And if you want to register another listener, you should create a class with Listener's implement, like for the main class :

public class MyListener implements Listener {

    // here all your event

}

Documentation

Related