Creating a GUI Inventory

Nov 6, 2018
Creating a GUI Inventory
  • Here is a snippet for creating a GUI Inventory. I simply begin by creating an inventory with nine slots. Then, I initialize any items in the inventory, adding an example sword and shovel. For this method, I use another called "createGuiItem", which allows me to create an item easily with a name, description, and a material. I have also added a method to open the inventory, and then an event handler for handling what happens when items are clicked.

    Many people want to create a system like this in their plugins, but they feel they have to ask in the development section first. With this, you can start simple, and add to it as you wish.

    Code (Text):
    public class Examples implements Listener{
     
        // Create a new inventory, with no owner, a size of nine, called example
        private final Inventory inv;
     
        public Examples() {
            inv = Bukkit.createInventory(null, 9, "Example");
        }

        // You can call this whenever you want to put the items in
        public void initializeItems() {
            inv.addItem(createGuiItem("Example Sword", new ArrayList<String>(Arrays.asList("This is an example!")), Material.DIAMOND_SWORD));
            inv.addItem(createGuiItem("Example Shovel", new ArrayList<String>(Arrays.asList("This is an example!")), Material.DIAMOND_SPADE));
        }
     
        // Nice little method to create a gui item with a custom name, and description
        public ItemStack createGuiItem(String name, ArrayList<String> desc, Material mat) {
            ItemStack i = new ItemStack(mat, 1);
            ItemMeta iMeta = i.getItemMeta();
            iMeta.setDisplayName(name);
            iMeta.setLore(desc);
            i.setItemMeta(iMeta);
            return i;
        }
     
        // You can open the inventory with this
        public void openInventory(Player p) {
            p.openInventory(inv);
            return;
        }
     
        // Check for clicks on items
        @EventHandler
        public void onInventoryClick(InventoryClickEvent e) {
            String invName = e.getInventory().getName();
            if (!invName.equals(inv.getName())) {
                return;
            }
            if (e.getClick().equals(ClickType.NUMBER_KEY)){
                 e.setCancelled(true);
            }
            e.setCancelled(true);

            Player p = (Player) e.getWhoClicked();
            ItemStack clickedItem = e.getCurrentItem();

            // verify current item is not null
            if (clickedItem == null || clickedItem.getType().equals(Material.AIR)) return;

            // Using slots click is a best option for your inventory click's
            if (e.getRawSlot() == 10) p.sendMessage("You clicked at slot " + 10);
        }
    }
  • Loading...
  • Loading...