Skip to content

Creating a dialog

Lucy Poulton edited this page Jul 31, 2023 · 1 revision

In this example, we'll put together a simple dialog. The completed dialog is included in the test mod.

1. Subclass Dialog and assign a theme

class MyFirstDialog(x: Int, y: Int) : Dialog(x, y), Themed by Theme.Active {}

where:

  • x and y are the co-ordinates at which the dialog will open at when added
  • Theme.Active is a theme to use. See Themes.

2. Pick a layout

Override layout() to return a layout, containing all the dialog's components.

Layouts dictate how elements are positioned within the dialog.

Name Description Source Builder
GridLayout Arranges items in a grid Vanilla GridLayoutBuilder
LinearLayout Evenly spreads items across the available space in one dimension Vanilla LinearLayoutBuilder
CanvasLayout Manually position items relative to an edge SheepLib Use apply

SheepLib includes some builders for vanilla layouts. They all define:

  • Factory functions, for example GridLayout(spacing: Int, builder: GridLayoutBuilder.() -> Unit)
  • Themed extension builder functions, for example Themed.grid(builder: GridLayoutBuilder.() -> Unit)

In this example, we'll use a grid layout.

3. Add components

We'll use GridLayoutBuilder to add some text and a button.

override fun layout() = grid {
    // Some static text.
    StringWidget(Component.literal("Hello world!"), Minecraft.getInstance().font).at(0, 0)

    // A close button.
    ThemedButton(
        Component.literal("Close"),
        // Dialogs implement Themed, it's good practice to use it directly to theme elements 
        theme =  this@MyFirstDialog 
    ) {
        // Button callback - close the dialog.
        close()
    }.at(1, 0)

    // GridLayoutBuilder has some nice ways of adding components
    // without having to give them all row and column values manually,
    // but that's outside the scope of this example.
    // Check GridLayoutBuilder javadocs for more info.
}

4. Add a title widget (optional)

A title widget is a special kind of widget that sits outside the layout. It's positioned at the very top of the dialog, with no spacing, and spans the dialog's entire width.

SheepLib itself provides one title widget implementation, TextTitleWidget, that shows a line of text with an optional close button.

You can set a title widget by overriding title:

override val title = TextTitleWidget(this, Component.literal("Hello!"))

5. Instantiate and open the dialog

Whenever you want to open a dialog, instantiate your class, and add it to DialogContainer.

DialogContainer += MyFirstDialog(10, 10)

Screenshot 2023-07-31 at 23 21 58