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.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.
*/
public class CycleItem extends BaseItem {
private final Consumer<Integer> stateChangeHandler;
private final ItemProvider[] states;
private int state;
public CycleItem(@Nullable Consumer<Integer> stateChangeHandler, @NotNull ItemProvider... states) {
this.stateChangeHandler = stateChangeHandler;
public CycleItem(@NotNull ItemProvider... states) {
this(0, states);
}
public CycleItem(int startState, @NotNull ItemProvider... 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
@ -32,22 +48,27 @@ public class CycleItem extends BaseItem {
@Override
public void handleClick(ClickType clickType, Player player, InventoryClickEvent event) {
if (clickType.isLeftClick()) cycle(true);
else if (clickType.isRightClick()) cycle(false);
if (clickType.isLeftClick()) cycle(player, true);
else if (clickType.isRightClick()) cycle(player, false);
}
public void cycle(boolean forward) {
cycle(null, forward);
}
private void cycle(@Nullable Player player, boolean forward) {
if (forward) {
if (++state == states.length) state = 0;
} else {
if (--state < 0) state = states.length - 1;
}
handleStateChange();
handleStateChange(player, state);
notifyWindows();
}
private void handleStateChange() {
if (stateChangeHandler != null) stateChangeHandler.accept(state);
notifyWindows();
protected void handleStateChange(@Nullable Player player, int state) {
// empty
}
public int getState() {