Solved I need help with my Inventory click event!

Discussion in 'Plugin Development' started by Jacob00524, Jul 23, 2019.

Thread Status:
Not open for further replies.
  1. Offline

    Jacob00524

    Hello,

    I need help with my inventory click event. The idea of it is when i type /kits as a command it will open an inventory and i can click on the kit icon/item and it can't be taken out of the inventory and it will call kit "kitname" method. So far i have created the inventory and the items show up, but when i click them they don't do anything and they can be taken. (I already have the kit stuff set up!) Any help would be greatly appreciated.
    Code:
    package Factions;
    
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    import java.util.Map;
    
    import org.bukkit.Bukkit;
    import org.bukkit.ChatColor;
    import org.bukkit.Material;
    import org.bukkit.Sound;
    import org.bukkit.command.Command;
    import org.bukkit.command.CommandExecutor;
    import org.bukkit.command.CommandSender;
    import org.bukkit.configuration.ConfigurationSection;
    import org.bukkit.configuration.file.FileConfiguration;
    import org.bukkit.enchantments.Enchantment;
    import org.bukkit.entity.Player;
    import org.bukkit.event.EventHandler;
    import org.bukkit.event.inventory.InventoryClickEvent;
    import org.bukkit.inventory.Inventory;
    import org.bukkit.inventory.ItemStack;
    import org.bukkit.inventory.PlayerInventory;
    import org.bukkit.inventory.meta.ItemMeta;
    
    public class KitsManager implements CommandExecutor
    {
        private Main plugin;
        Inventory kitMenu = Bukkit.createInventory(null, 54, "Kits");
    
        public KitsManager(Main plugin) {
            this.plugin    = plugin;
            plugin.getCommand("kits").setExecutor(this);
            createMenu();
        }
        public void createKit(Player p, String kitName) {
            FileConfiguration config    = plugin.getConfig(); // Replace with the configuration file YOU want to use.
            PlayerInventory inv            = p.getInventory();
            // Now, before creating a kit, we need to make sure that the kit does not already exist.
            if (config.getConfigurationSection("kits." + kitName) != null) {
                p.sendMessage(kitName + " already exists!");
                return;
            }
            // We'll be using this path a lot to set items and stuff for the kits.
            String path = "kits." + kitName + ".";
            // Create a new Configuration Section
            config.createSection("kits." + kitName);
            /*
            * This is our for loop. It iterates through all the main inventory slots (Slots 0 - 35).
            * If a player has an item there, it will set it in the config.
            */
            for (int i = 0; i < 36; i++) {
                ItemStack is = inv.getItem(i);
                // If null or air, continue, because we don't care anymore since that just wastes space in the config.
                if (is == null || is.getType() == Material.AIR)
                    continue;
                // For each number, representing the inventory slot, we'll need to set several things such as the material.
                String slot = path + "items." + i;
                // Material.GOLD_INGOT ==> gold_ingot - This is unnecessary but looks better in the config and easier to read (in my opinion)
                config.set(slot + ".type", is.getType().toString().toLowerCase());
                config.set(slot + ".amount", is.getAmount());
                // Do not go any further if the item does not have any item meta.
                if (!is.hasItemMeta())
                    continue;
                /*
                * Now, we are just going to be checking individually if there is a name, lore, etc..
                */
                if (is.getItemMeta().hasDisplayName())
                    config.set(slot + ".name", is.getItemMeta().getDisplayName());
                if (is.getItemMeta().hasLore())
                    config.set(slot + ".lore", is.getItemMeta().getLore());
                // We are going to be adding enchantments as a stringlist.
                if (is.getItemMeta().hasEnchants()) {
                    Map<Enchantment, Integer> enchants = is.getEnchantments();
                    List<String> enchantList = new ArrayList<String>();
                    for (Enchantment e : is.getEnchantments().keySet()) {
                        int level = enchants.get(e);
                        enchantList.add(e.getName().toLowerCase() + ":" + level);
                    }
                    config.set(slot + ".enchants", enchantList);
                }
                // While 'continue;' isn't always necessary, I feel it's good practice to put it.
                continue;
            }
            /*
            * Since ternary operators can be confusing: If the armor piece is not
            * null, set it to the player's helmet. If it is null, set the config
            * key to air (representing the material air).
            *
            * Material.DIAMOND_HELMET => diamond_helmet
            */
            config.set(path + "armor.helmet", inv.getHelmet() != null ? inv
                    .getHelmet().getType().toString().toLowerCase() : "air");
            config.set(path + "armor.chestplate", inv.getChestplate() != null ? inv
                    .getChestplate().getType().toString().toLowerCase() : "air");
            config.set(path + "armor.leggings", inv.getLeggings() != null ? inv
                    .getLeggings().getType().toString().toLowerCase() : "air");
            config.set(path + "armor.boots", inv.getBoots() != null ? inv
                    .getBoots().getType().toString().toLowerCase() : "air");
            plugin.saveConfig();
            // Therefore, Operators have all kits by default.
            //NOTE: For the purpose of this tutorial, I will not be covering per-kit permissions unless I get many requests to add it.
        }
        /*
        * This method has deprecation warnings: p.updateInventory() is the only deprecated method.
        */
        @SuppressWarnings("deprecation")
        public void giveKit(Player p, String kitName) {
            FileConfiguration config = plugin.getConfig();
            // Sanity-checks
            if (config.getConfigurationSection("kits." + kitName) == null) {
                p.sendMessage(kitName + " does not exist!");
                return;
            }
            // Clear the player's inventory so they don't have extra items
            p.getInventory().clear();
            // Again, we need this path.
            String path = "kits." + kitName + ".";
            // Because it exists, we can use the configuration section.
            ConfigurationSection s = config.getConfigurationSection(path + "items");
            // Loop through the different keys directly next in line, so to speak.
            for (String str : s.getKeys(false)) {
                int slot = Integer.parseInt(str);
                // Return (continue) if the slot is an invalid number.
                if (0 > slot && slot > 36)
                    return;
                // Just cast some variables for easy use. Our null checks are later on.
                String string            = path + "items." + slot + ".";
                String type            = config.getString(string + "type");
                String name            = config.getString(string + "name");
                List<String> lore        = config.getStringList(string + "lore");
                List<String> enchants    = config.getStringList(string + "enchants");
                int amount              = config.getInt(string + "amount");
                // If you remember, we converted the name of the material to
                // lowercase. Because it's an enum we need to reconvert it.
                ItemStack is    = new ItemStack(Material.matchMaterial(type.toUpperCase()), amount);
                ItemMeta im    = is.getItemMeta();
                // Continue if there is no itemMeta.
                if (im == null)
                    continue;
                if (name != null)
                    im.setDisplayName(ChatColor.translateAlternateColorCodes('&', name));
                if (lore != null)
                    im.setLore(Arrays.asList(ChatColor.translateAlternateColorCodes('&', lore.toString())));
                if (enchants != null) {
                    // We attached enchantments to their levels - Now we need to
                    // splice it. So we need to loop through each string list.
                    for (String s1 : enchants) {
                        String[] indiEnchants = s1.split(":");
                        im.addEnchant(Enchantment.getByName(indiEnchants[0].toUpperCase()), Integer.parseInt(indiEnchants[1]), true);
                    }
                }
                is.setItemMeta(im);
                p.getInventory().setItem(slot, is);
            }
            // We also need to give them armor.
            String helmet        = config.getString(path + "armor.helmet").toUpperCase();
            String chestplate    = config.getString(path + "armor.chestplate").toUpperCase();
            String leggings    = config.getString(path + "armor.leggings").toUpperCase();
            String boots        = config.getString(path + "armor.boots").toUpperCase();
            // If each is null, set their armor piece to air. Else, set it to the config key.
            p.getInventory().setHelmet(new ItemStack(helmet != null ? Material.matchMaterial(helmet) : Material.AIR));
            p.getInventory().setChestplate(new ItemStack(chestplate != null ? Material.matchMaterial(chestplate) : Material.AIR));
            p.getInventory().setLeggings(new ItemStack(leggings != null ? Material.matchMaterial(leggings) : Material.AIR));
            p.getInventory().setBoots(new ItemStack(boots != null ? Material.matchMaterial(boots) : Material.AIR));
            p.updateInventory();
        }
       
       
        public Main getPlugin() {
            return plugin;
        }
       
        public void createMenu() {
            kitMenu.setItem(10, new ItemStack(Material.DIRT, 1));
            kitMenu.setItem(11, new ItemStack(Material.IRON_NUGGET, 1));
            kitMenu.setItem(12, new ItemStack(Material.IRON_INGOT, 1));
            kitMenu.setItem(13, new ItemStack(Material.GOLD_INGOT, 1));
            kitMenu.setItem(14, new ItemStack(Material.DIAMOND, 1));
            kitMenu.setItem(15, new ItemStack(Material.EMERALD, 1));
            kitMenu.setItem(16, new ItemStack(Material.DEAD_BUSH, 1));
            kitMenu.setItem(19, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(20, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(21, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(22, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(23, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(24, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(25, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(28, new ItemStack(Material.IRON_SWORD, 1));
            kitMenu.setItem(29, new ItemStack(Material.IRON_CHESTPLATE, 1));
            kitMenu.setItem(31, new ItemStack(Material.ARROW, 1));
            kitMenu.setItem(32, new ItemStack(Material.DIAMOND_SWORD, 1));
            kitMenu.setItem(33, new ItemStack(Material.GOLDEN_SWORD, 1));
            kitMenu.setItem(28, new ItemStack(Material.BOW, 1));
            kitMenu.setItem(0, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(1, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(2, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(3, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(4, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(5, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(6, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(7, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(8, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(9, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(17, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(18, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(26, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(27, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(35, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(36, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(44, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(45, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(46, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(47, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(48, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(49, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(50, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(51, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(52, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(53, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(37, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(38, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(39, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(40, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(41, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(42, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(43, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            kitMenu.setItem(44, new ItemStack(Material.BLUE_STAINED_GLASS_PANE, 1));
            ((Player) kitMenu).updateInventory();
        }
       
        @EventHandler
        public void onInventoryClick(InventoryClickEvent event) {
            Player player = (Player) event.getWhoClicked(); // The player that clicked the item
            player.updateInventory();
            ItemStack clicked = event.getCurrentItem(); // The item that was clicked
            Inventory inventory = event.getInventory(); // The inventory that was clicked in
            if (((Command) inventory).getName().equals(((Command) kitMenu).getName())) { // The inventory is our custom Inventory
                if (clicked.getType() == Material.DIRT) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Starter");
                }
                if (clicked.getType() == Material.IRON_NUGGET) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Donator");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.IRON_INGOT) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Tier 1");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.GOLD_INGOT) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Tier 2");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.DIAMOND) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Tier 3");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.EMERALD) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Tier 4");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.DEAD_BUSH) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "GOD");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.IRON_SWORD) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Adventurer");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.IRON_CHESTPLATE) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Knight");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.ARROW) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Archer");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.DIAMOND_SWORD) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Mage");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.GOLDEN_SWORD) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Assasin");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.BOW) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    giveKit(player, "Soldeir");
                    ((Player) kitMenu).updateInventory();
                }
                if (clicked.getType() == Material.BLUE_STAINED_GLASS_PANE) { // The item that the player clicked it dirt
                    event.setCancelled(true); // Make it so the dirt is back in its original spot
                    player.closeInventory(); // Closes there inventory
                    player.playSound(player.getLocation(), Sound.BLOCK_ANVIL_FALL, 10, 1);
                    ((Player) kitMenu).updateInventory();
                }
            }
            ((Player) kitMenu).updateInventory();
        }
        public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
           
            if(!(sender instanceof Player)) {
                sender.sendMessage(ChatColor.RED + "Error you have to be a player to execute this commands. If you think this is an error contact server staff.");
                return false;
            }
           
            Player player = (Player) sender;
           
            player.openInventory(kitMenu);
           
            return false;
        }
    }
    New to threads and forums sorry for the noobness.
     
  2. Offline

    Machine Maker

    So it looks like you need some debugging. Best play to start is put some
    PHP:
    System.out.println("test1")
    around your InventoryClickEvent and see which ones get run and which ones don't
    (increment the test1 to test2 and so on)
    Place them at various points and you can start to find where the issue is.
     
    Jacob00524 likes this.
  3. Offline

    KarimAKL

    @Jacob00524
    1. It doesn't look to me like your class implements Listener
    2. It doesn't seem like you are registering the listener
    3. For your 'createMenu()' method, you can set the items you want and then loop the inventory after that, check if the slot is empty and if so, set your stained glass at that slot.
     
    Jacob00524 likes this.
  4. Offline

    Jacob00524

    Thanks for the fast reply. I just implemented the listener and registered it. i used the top line to implement it and the bottom line to register it. Think it implemented/registered properly. My onInventoryClick event didn't send any test messages. I put the messages at the top of the method. I guess it is not being called? Do i have to call it manually?


    Code:
    public class KitsManager implements CommandExecutor, Listener {
    
    
    }
    Bukkit.getServer().getPluginManager().registerEvents(this.Listener, (Plugin) this);
    [cake][cake][cake][cake]
     
    Last edited: Jul 23, 2019
  5. Offline

    Machine Maker

    @Jacob00524 You need to register the event in the onEnable() method.

    Also, you can just do
    Code:
    Bukkit.getServer().getPluginManager().registerEvents(this, this);
    
    if the Listener is in the same file as the onEnable
     
    KarimAKL likes this.
  6. Offline

    KarimAKL

    @Jacob00524 If it's all in the same class you can simply do registerEvents(this, this)
     
  7. Offline

    Jacob00524

    SOLVED

    thanks

    In case anyone is curious i has the wrong listener. I was implementing Listener which is part of Java. I had to implement org.bukkit.event.Listener!
     
    KarimAKL likes this.
Thread Status:
Not open for further replies.

Share This Page