Skip to content

Instantly share code, notes, and snippets.

Created June 27, 2014 08:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/93cfe1803e2be9adb0ed to your computer and use it in GitHub Desktop.
Save anonymous/93cfe1803e2be9adb0ed to your computer and use it in GitHub Desktop.
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.entity.HumanEntity;
import org.bukkit.entity.Player;
import org.bukkit.event.inventory.InventoryAction;
import org.bukkit.inventory.Inventory;
import org.bukkit.inventory.InventoryHolder;
public class Menu implements InventoryHolder
{
private Menu parent;
private Inventory inventory;
private boolean closeOnClickOutside;
private HashMap<Integer, MenuItem> items;
public Menu(Menu menu, String title, int rows)
{
this(title, rows);
this.parent = menu;
}
public Menu(String title, int rows)
{
this.inventory = Bukkit.createInventory(this, rows * 9, title);
this.closeOnClickOutside = false;
this.items = new HashMap<Integer, MenuItem>();
}
public Menu(String title)
{
this(title, 1);
}
@Override
public Inventory getInventory()
{
return inventory;
}
public int getSize()
{
return inventory.getSize();
}
public Menu getParent()
{
return parent;
}
public MenuItem getItem(int slot)
{
return items.get(slot);
}
public void setCloseOnClickOutside(boolean bool)
{
this.closeOnClickOutside = bool;
}
public void addItem(int slot, MenuItem item)
{
item.setMenu(this);
items.put(slot, item);
update();
}
public void removeItem(int slot)
{
items.remove(slot);
update();
}
public void open(HumanEntity human)
{
human.openInventory(inventory);
}
public void close(HumanEntity human)
{
human.closeInventory();
}
public void onClick(Player player, InventoryAction actionType, int slot)
{
// Check to see if there is a valid item in the slot clicked
if (isItemInSlot(slot))
{
MenuItem menuItem = getItem(slot);
// Before calling the menu item's click handler lets make sure it
// has one!
if (menuItem.hasClickHandler())
{
menuItem.getClickHandler()
.onClick(menuItem, player, actionType);
}
// After the menu item has been clicked should we close the
// inventory?
if (menuItem.shouldCloseMenuOnSelection())
{
close(player);
}
}
}
@SuppressWarnings("deprecation")
public void update()
{
inventory.clear();
for (int slot : items.keySet())
{
MenuItem menuItem = getItem(slot);
inventory.setItem(slot, menuItem.getIcon());
}
for (HumanEntity human : inventory.getViewers())
{
if (human instanceof Player)
{
Player player = (Player) human;
player.updateInventory();
}
}
}
public void cleanUp()
{
items.clear();
items = null;
inventory = null;
parent = null;
}
public boolean closeOnClickOutside()
{
return closeOnClickOutside;
}
public boolean isItemInSlot(int slot)
{
return getItem(slot) != null;
}
public boolean hasParent()
{
return getParent() != null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment