Skip to content

Java compatibility

MattMX edited this page Feb 14, 2024 · 6 revisions

KtGui is fully compatible with Java. Specific alternative methods have been added to help to try and reduce boiletplate when in Java.

These alternative methods are marked with annotation @JavaCompatibility to differ from when using Kotlin.

Creating a GUI

Almost the same as Kotlin, but we can't use the gui block. Instead we can instantiate a new GuiScreen (or whatever extends that) and use the method addChild as a builder to add buttons.

If you want you can still call GuiButton#childOf(GuiScreen parent) for the same effect.

GuiScreen gui = new GuiScreen(Component.text("Title"), 3)
  .addChild(
    new GuiButton(Material.DIRT)
      .named(Component.text("Item"))
      .click(ClickType.LEFT, (event) -> event.getPlayer().sendMessage(Component.text("clicked")))
      .lore(Component.text("Lore line one"))
      .lore(Component.text("Lore line two"))
      .slot(3)
);

The following methods in GuiButton are marked with @JavaCompatibility

  • click(ClickType type, Consumer<ButtonClickedEvent> callback) add a click callback, builder method for calling .getClick().handleClick(type, callback)
  • lore(Component... line) add many lines of lore

Signals

Again, very similar to Kotlin, but introduces a bit more boilerplate.

// Would usually call extension method `signal` in kotlin, but java cannot use extension methods.
// might change this later but i didnt want to affect imports
Signal<String> signalExample = gui.createSignal("mattmx");

gui.effectBlock(() -> new GuiButton(Material.DIAMOND)
  .named(Component.text(signalExample.get()))
  //                                              vvvvv Must call `Signal` methods instead of relying on delegation like we would in kotlin
  .click(ClickType.LEFT, (event) -> signalExample.setTo(signalExample.get().equals("foo") ? "bar" : "foo"))
  .slot(5)
  .childOf(gui)
);

Events DSL

Java methods have been added for better support. Instead of using event, you should use javaEvent

// There are multiple methods to supply `EventPriority` and `ignoreCancelled`.
javaEvent(plugin, PlayerJoinEvent.class, (event) -> {
  event.getPlayer().sendMessage(Component.text("welcome!"));
  return null;
});

todo command builders, scoreboard

Clone this wiki locally