Inventory - SimonFlash/TeslaPowered GitHub Wiki
The inventory package contains the core classes required for basic gui implementations. Every gui consists of three primary pieces: a representing view, the elements in that view, and the layout of the elements onto the view. These concepts are represented in the View
, Element
, and Layout
classes.
An Element
is an individual component of a gui for a single slot that contains an ItemStackSnapshot
for the display item and a Consumer<Player>
as the action. Let's demonstrate the creation of an Element
.
ItemStack item = ItemStack.of(ItemTypes.BLAZE_POWDER, 1);
Consumer<Player> consumer = player -> player.sendMessage(Text.of("Elements are awesome!"));
Element element = Element.of(item, consumer);
An
Element
is immutable - theItemStack
is stored internally as anItemStackSnapshot
and thus any changes made to theItemStack
afterwards will not affect thisElement
s state.
Additionally, an empty Element
(Element.of(ItemStack.empty())
) can be obtained with the static method Element.empty()
. This element may be used to 'reset' a slot and is non-operational.
Before we can discuss View
s, we need to start with a way to define what slot an Element
represents. To do this, we use the Layout
class to server as a holder and provide a series of utility methods for creating layouts. Let's take a look at a simple layout with a couple of elements.
Element stone = Element.of(ItemStack.of(ItemTypes.STONE, 1));
Element dirt = Element.of(ItemStack.of(ItemTypes.DIRT, 2));
Element grass = Element.of(ItemStack.of(ItemTypes.GRASS, 3));
Layout layout = Layout.builder()
.slot(stone, 0)
.slot(dirt, 1)
.slot(grass, 2)
.build();
Like an
Element
, aLayout
instance is also immutable.
The Layout.Builder
class also has a variety of utility methods for common actions. However, note that many of these require a dimension for the layout to be set in order to calculation slot positions. Here is a simple example of some of the available utility methods.
Layout layout = Layout.builder()
.dimension(9, 3)
.border(stone)
.slots(dirt, 11, 15)
.center(grass)
.build();
Lastly, the View
class is the core of the gui and is responsible for managing the inventory, processing events, and handling other various actions. A view may have it's inventory defined or updated live and may be shared between players. Once a view is created, it can be defined or updated with a layout.
PluginContainer container;
View view = View.of(InventoryArchetypes.CHEST, container);
view.define(layout);
View#define
andView#update
return the same view and may be used fluently.
Now that the view has been defined, you can open the view for a player using View#open
and close it with View#close
. If you would like to prevent a player from closing the gui themselves, you can use view.setCloseable(false)
- just remember to undo it or close the view manually so they don't get stuck!