Creating a GUI Inventory - Historical

Applied By Minesuchtiiii: Aug 3, 2019 at 11:59 AM

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 helmet. 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 (Java):

public class ExampleGui implements InventoryHolder, Listener {
    // Create a new inventory, with "this" owner for comparison with other inventories, a size of nine, called example
    private final Inventory inv;

    public ExampleGui() {
        inv = Bukkit.createInventory(this, 9, "Example");
    }

    @NotNull
    @Override
    public Inventory getInventory() {
        return inv;
    }

    // You can call this whenever you want to put the items in
    public void initializeItems() {
        inv.addItem(createGuiItem(Material.DIAMOND_SWORD, "Example Sword", "§aFirst line of the lore", "§bSecond line of the lore"));
        inv.addItem(createGuiItem(Material.IRON_HELMET, "§bExample Helmet", "§aFirst line of the lore", "§bSecond line of the lore"));
    }

    // Nice little method to create a gui item with a custom name, and description
    private ItemStack createGuiItem(Material material, String name, String...lore) {
        ItemStack item = new ItemStack(material, 1);
        ItemMeta meta = item.getItemMeta();
        meta.setDisplayName(name);
       ArrayList<String> metalore = new ArrayList<String>();        

       for(String lorecommnets : lore) {

      metalore.add(lorecomments);

}

       meta.setLore(metalore);
        item.setItemMeta(meta);
        return item;
    }

    // You can open the inventory with this
    public void openInventory(Player p) {
        p.openInventory(inv);
    }

    // Check for clicks on items
    @EventHandler
    public void onInventoryClick(InventoryClickEvent e) {
        if (inv.getHolder() != this) {
            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() == 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);
    }
}