Update CycleItem.java

This commit is contained in:
NichtStudioCode 2021-12-30 23:30:18 +01:00
parent 76a846f753
commit ab913eed3c

@ -8,21 +8,37 @@ import org.bukkit.event.inventory.InventoryClickEvent;
import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Nullable;
import java.util.function.Consumer; import java.util.function.BiConsumer;
/** /**
* An {@link Item} that cycles through a predefined array of {@link ItemProvider}s when clicked. * An {@link Item} that cycles through a predefined array of {@link ItemProvider}s when clicked.
*/ */
public class CycleItem extends BaseItem { public class CycleItem extends BaseItem {
private final Consumer<Integer> stateChangeHandler;
private final ItemProvider[] states; private final ItemProvider[] states;
private int state; private int state;
public CycleItem(@Nullable Consumer<Integer> stateChangeHandler, @NotNull ItemProvider... states) { public CycleItem(@NotNull ItemProvider... states) {
this.stateChangeHandler = stateChangeHandler; this(0, states);
}
public CycleItem(int startState, @NotNull ItemProvider... states) {
this.states = states; this.states = states;
this.state = startState;
}
public static CycleItem withStateChangeHandler(BiConsumer<Player, Integer> stateChangeHandler, @NotNull ItemProvider... states) {
return withStateChangeHandler(stateChangeHandler, 0, states);
}
public static CycleItem withStateChangeHandler(BiConsumer<Player, Integer> stateChangeHandler, int startState, @NotNull ItemProvider... states) {
return new CycleItem(startState, states) {
@Override
protected void handleStateChange(@Nullable Player player, int state) {
stateChangeHandler.accept(player, state);
}
};
} }
@Override @Override
@ -32,22 +48,27 @@ public class CycleItem extends BaseItem {
@Override @Override
public void handleClick(ClickType clickType, Player player, InventoryClickEvent event) { public void handleClick(ClickType clickType, Player player, InventoryClickEvent event) {
if (clickType.isLeftClick()) cycle(true); if (clickType.isLeftClick()) cycle(player, true);
else if (clickType.isRightClick()) cycle(false); else if (clickType.isRightClick()) cycle(player, false);
} }
public void cycle(boolean forward) { public void cycle(boolean forward) {
cycle(null, forward);
}
private void cycle(@Nullable Player player, boolean forward) {
if (forward) { if (forward) {
if (++state == states.length) state = 0; if (++state == states.length) state = 0;
} else { } else {
if (--state < 0) state = states.length - 1; if (--state < 0) state = states.length - 1;
} }
handleStateChange();
handleStateChange(player, state);
notifyWindows();
} }
private void handleStateChange() { protected void handleStateChange(@Nullable Player player, int state) {
if (stateChangeHandler != null) stateChangeHandler.accept(state); // empty
notifyWindows();
} }
public int getState() { public int getState() {