Skip to content

Buttons

Juuxel edited this page Jul 23, 2022 · 6 revisions

Buttons are everywhere in Minecraft: in the title screen, the pause menu, and — you guessed it — LibGui screens!

There are two types of buttons: the plain and simple WButton, and the switch-like WToggleButton.

Regular buttons (WButton)

WButton represents a normal Minecraft-style button that runs code when you click it.

WButton button = new WButton(Text.literal("Hello, world!"));
button.setOnClick(() -> {
    // This code runs on the client when you click the button.
    System.out.println("Button clicked!");
});

When adding a button to a panel you must provide a width so that it renders correctly:

// Widget, X, Y, Width, Height
root.add(button, 20, 20, 200, 20);

Result:
Picture of the resulting button.

Note that buttons are always 20 pixels high.

Adding an icon

Since LibGui 2.2.0, buttons can also have small icons drawn on them. Currently, icons can be a texture (TextureIcon) or an item (ItemIcon).

// Paints a sandstone block as the button's icon:
button.setIcon(new ItemIcon(new ItemStack(Items.SANDSTONE)));

Result:
Picture of the resulting button with a sandstone icon.

Toggle buttons (WToggleButton)

WToggleButton represents a simple button to toggle between two states. By default it renders as an on/off switch, but you can provide two Textures or Identifiers for its active and non-active states respectively.

WToggleButton toggleButton = new WToggleButton(Text.literal("This is a toggle button."));
toggleButton.setOnToggle(on -> {
    // This code runs on the client when you toggle the button.
    System.out.println("Toggle button toggled to " + (on ? "on" : "off"));
});

Result:
Picture of the resulting toggle button.

Toggle buttons are always 18 pixels by 18 pixels in size.