From f0d1ac5eaf4d55caa7ff308d09668f8b1a46b086 Mon Sep 17 00:00:00 2001 From: NichtStudioCode <51272202+NichtStudioCode@users.noreply.github.com> Date: Wed, 31 Mar 2021 13:47:35 +0200 Subject: [PATCH] Add itemUpdateHandler --- .../virtualinventory/VirtualInventory.java | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/src/main/java/de/studiocode/invui/virtualinventory/VirtualInventory.java b/src/main/java/de/studiocode/invui/virtualinventory/VirtualInventory.java index c6b02b6..04d1fc9 100644 --- a/src/main/java/de/studiocode/invui/virtualinventory/VirtualInventory.java +++ b/src/main/java/de/studiocode/invui/virtualinventory/VirtualInventory.java @@ -12,6 +12,7 @@ import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; +import java.util.function.Consumer; public class VirtualInventory implements ConfigurationSerializable { @@ -20,6 +21,7 @@ public class VirtualInventory implements ConfigurationSerializable { private final UUID uuid; private int size; private ItemStack[] items; + private Consumer itemUpdateHandler; /** * Creates a new {@link VirtualInventory}. @@ -396,7 +398,7 @@ public class VirtualInventory implements ConfigurationSerializable { private int findFullSlot(ItemStack itemStack) { for (int i = 0; i < items.length; i++) { ItemStack currentStack = items[i]; - if (currentStack != null + if (currentStack != null && currentStack.getAmount() == currentStack.getMaxStackSize() && currentStack.isSimilar(itemStack)) return i; } @@ -471,8 +473,8 @@ public class VirtualInventory implements ConfigurationSerializable { private ItemUpdateEvent createAndCallEvent(int index, Player player, ItemStack previousItemStack, ItemStack newItemStack) { ItemUpdateEvent event = new ItemUpdateEvent(this, index, player, previousItemStack, newItemStack); + if (itemUpdateHandler != null) itemUpdateHandler.accept(event); Bukkit.getPluginManager().callEvent(event); - return event; } @@ -485,6 +487,19 @@ public class VirtualInventory implements ConfigurationSerializable { return uuid; } + /** + * Sets the item update handler which is an alternative for using + * Bukkit's event system for handling item updates in this virtual + * inventory. The item update handler is called before the Bukkit event + * is fired and all changes made are visible when catching Bukkit's + * event. + * + * @param itemUpdateHandler The item update handler + */ + public void setItemUpdateHandler(Consumer itemUpdateHandler) { + this.itemUpdateHandler = itemUpdateHandler; + } + /** * Serializes this {@link VirtualInventory} to a {@link Map} *