Bukkit 事件 InventoryClickEvent 不起作用

Bukkit event InventoryClickEvent doesn't work

我想制作一个里面有钻石的 GUI(单行库存)。但是当点击钻石时,似乎什么也没有发生。我很确定是 GuiCommand#onInventoryClick(InventoryClickEvent e) 或只是 InventoryClickEvent 不起作用。有人可以帮忙吗?

这是我的代码:

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
    }
}

这是我的主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!");
    }
}

您需要使用 registerEvents() 注册活动。例如,在您的 onEnable():

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

将 CommandExecutors 和 Listeners 拆分成单独的 类。

通常是个好习惯