package de.lucas.litematica.gui; import net.minecraft.client.gui.GuiGraphics; import net.minecraft.client.gui.components.Button; import net.minecraft.client.gui.components.EditBox; import net.minecraft.client.gui.screens.Screen; import net.minecraft.network.chat.Component; import org.lwjgl.glfw.GLFW; import java.util.function.Consumer; /** Small dialog asking for one line of text (used for renaming). */ public class TextInputScreen extends Screen { private final Screen parent; private final String initial; private final Consumer onConfirm; private EditBox input; public TextInputScreen(Screen parent, Component title, String initial, Consumer onConfirm) { super(title); this.parent = parent; this.initial = initial; this.onConfirm = onConfirm; } @Override protected void init() { int cx = this.width / 2; int y = this.height / 2 - 20; this.input = new EditBox(this.font, cx - 100, y, 200, 20, this.title); this.input.setMaxLength(128); this.input.setValue(this.initial); this.addRenderableWidget(this.input); this.setInitialFocus(this.input); this.addRenderableWidget(Button.builder(Component.translatable("gui.done"), b -> this.confirm()) .bounds(cx - 100, y + 28, 98, 20).build()); this.addRenderableWidget(Button.builder(Component.translatable("gui.cancel"), b -> this.onClose()) .bounds(cx + 2, y + 28, 98, 20).build()); } private void confirm() { String value = this.input.getValue().trim(); if (!value.isEmpty()) { this.onConfirm.accept(value); } this.onClose(); } @Override public boolean keyPressed(int keyCode, int scanCode, int modifiers) { if (keyCode == GLFW.GLFW_KEY_ENTER || keyCode == GLFW.GLFW_KEY_KP_ENTER) { this.confirm(); return true; } return super.keyPressed(keyCode, scanCode, modifiers); } @Override public void render(GuiGraphics graphics, int mouseX, int mouseY, float partialTick) { super.render(graphics, mouseX, mouseY, partialTick); graphics.drawCenteredString(this.font, this.title, this.width / 2, this.height / 2 - 40, 0xFFFFFF); } @Override public void onClose() { this.minecraft.setScreen(this.parent); } }