简体   繁体   中英

Bukkit event InventoryClickEvent doesn't work

I want to make a GUI (a one-line inventory) with a diamond inside. But when click on the diamond, nothing seems to happen. I'm pretty sure it's the GuiCommand#onInventoryClick(InventoryClickEvent e) or just the InventoryClickEvent that doesn't work. Can anyone help?

This is my code:

package net.itrature.guiplugin.commands;

import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.inventory.InventoryClickEvent;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.ItemStack;

public class GuiCommand implements CommandExecutor, Listener
{
    private Inventory inv;
    
    @Override
    public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args)
    {
        if (!(sender instanceof Player)) return true;
        if (args.length != 0) sender.sendMessage(ChatColor.RED + "Usage: /gui");
        
        inv = Bukkit.createInventory(null, 9);
        inv.setItem(4, new ItemStack(Material.DIAMOND));
        
        ((Player) sender).openInventory(inv);
        
        return true;
    }
    
    @EventHandler
    public void onInventoryClick(InventoryClickEvent event)
    {
        // Testing if the diamond is clicked
        if (event.getInventory() == inv && event.getCurrentItem().getType() == Material.DIAMOND)
            event.getWhoClicked().sendMessage("Diamond clicked!"); // Never occurs
    }
}

This is my main class:

package net.itrature.guiplugin;

import org.bukkit.plugin.java.JavaPlugin;

import net.itrature.guiplugin.commands.GuiCommand;

public class GuiPlugin extends JavaPlugin
{
    private static GuiPlugin plugin;
    
    @Override
    public void onEnable()
    {
        if (plugin != null) getLogger().warning("Plugin loaded twice!");
        else plugin = this;
        
        getCommand("gui").setExecutor(new GuiCommand());
        
        getLogger().info("Plugin enabled!");
    }
    
    @Override
    public void onDisable()
    {
        plugin = null;
        
        getLogger().info("Plugin disabled!");
    }
}

You need to register the events using registerEvents() . For example, in your onEnable() :

GuiCommand guiCommand = new GuiCommand();
getCommand("gui").setExecutor(guiCommand);
Bukkit.getPluginManager().registerEvents(guiCommand, this);

It's generally good practice to split up your CommandExecutors and Listeners into separate classes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM