### Basic MultiWindowTextGUI Setup Source: https://context7.com/mabe02/lanterna/llms.txt Sets up a basic GUI application using MultiWindowTextGUI. This example demonstrates creating a window, adding components, and handling blocking UI operations. ```java import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.screen.TerminalScreen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import com.googlecode.lanterna.terminal.Terminal; import com.googlecode.lanterna.gui2.*; public class GUISetup { public static void main(String[] args) throws Exception { Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // MultiWindowTextGUI uses the calling thread for all UI operations by default WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); BasicWindow window = new BasicWindow("Hello GUI"); window.setHints(java.util.Arrays.asList(Window.Hint.CENTERED)); Panel panel = new Panel(new LinearLayout(Direction.VERTICAL)); panel.addComponent(new Label("Welcome to Lanterna GUI!")); panel.addComponent(new Button("Close", window::close)); window.setComponent(panel); // Blocks until window.close() is called gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Start and Use TextGUI Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideStartTheGUI.md The `TextGUI` interface relies on the `Screen` object for its lifecycle. Ensure the `Screen` is started before using the GUI and stopped afterward. This example demonstrates the complete setup for using the GUI. ```java Terminal term = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(term); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); screen.startScreen(); // use GUI here until the GUI wants to exit screen.stopScreen(); ``` -------------------------------- ### Setup WindowBasedTextGUI for Dialogs Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/action_list_dialogs.md Initializes the terminal, screen, and WindowBasedTextGUI required for displaying dialogs. This setup must be completed before showing any dialogs. ```java // Setup terminal and screen layers Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // Setup WindowBasedTextGUI for dialogs final WindowBasedTextGUI textGUI = new MultiWindowTextGUI(screen); ``` -------------------------------- ### Setup WindowBasedTextGUI for Dialogs Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/file_dialogs.md Initializes the terminal, screen, and `WindowBasedTextGUI` which is required for displaying dialogs. Ensure this setup is done before creating any dialogs. ```java // Setup terminal and screen layers Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // Setup WindowBasedTextGUI for dialogs final WindowBasedTextGUI textGUI = new MultiWindowTextGUI(screen); ``` -------------------------------- ### Minimal CheckBox Example Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md A basic example of integrating a CheckBox into a Lanterna window, including adding a listener for state changes. Assumes GUI setup is handled elsewhere. ```java WindowBasedTextGUI gui = ...; // See using-gui.md for setup Panel content = new Panel(); content.addComponent(new Label("Options:")); CheckBox verbose = new CheckBox("Verbose output"); verbose.addListener(checked -> { // Enable/disable verbose logging }); content.addComponent(verbose); BasicWindow window = new BasicWindow("Demo"); window.setComponent(content); gui.addWindowAndWait(window); ``` -------------------------------- ### Create and Start Screen Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial04.md Obtains a Screen instance from the terminal factory and starts it, putting the terminal into private mode. This is essential before initializing the GUI. ```java screen = terminalFactory.createScreen(); screen.startScreen(); ``` -------------------------------- ### Initialize Terminal Factory and Screen Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial04.md Sets up the terminal factory and creates a screen instance. This is a prerequisite for starting the text GUI. ```java DefaultTerminalFactory terminalFactory = new DefaultTerminalFactory(); Screen screen = null; try { ``` -------------------------------- ### Minimal ScrollBar Usage Example Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates the basic setup and updating of a vertical ScrollBar. Ensure to keep the ScrollBar in sync with content changes and window resizing. ```java // Create a vertical scrollbar and place it next to your scrolling content ScrollBar vbar = new ScrollBar(Direction.VERTICAL); // In your component setup / model update vbar.setScrollMaximum(totalRowsInModel); vbar.setViewSize(visibleRowCount); vbar.setScrollPosition(currentTopRowOffset); // Add to layout (example with a 2-column GridLayout: content | bar) Panel panel = new Panel(new GridLayout(2)); panel.addComponent(contentComponent); panel.addComponent(vbar); // When content scrolls or the window resizes, keep the bar in sync vbar.setScrollMaximum(totalRowsInModel); vbar.setViewSize(visibleRowCount); vbar.setScrollPosition(currentTopRowOffset); ``` -------------------------------- ### Button Layout Example Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates how to create and arrange buttons within a GridLayout in a Lanterna window. Assumes a TextGUI is available. ```java import com.googlecode.lanterna.gui2.*; public class ButtonLayoutExample { public static void main(String[] args) { // Assume a TextGUI is available WindowBasedTextGUI gui = obtainGui(); Panel content = new Panel(new GridLayout(2)); Button ok = new Button("OK", () -> gui.getActiveWindow().close()); Button cancel = new Button("Cancel", () -> System.out.println("Canceled")); content.addComponent(ok); content.addComponent(cancel); BasicWindow window = new BasicWindow("Example"); window.setComponent(content); gui.addWindowAndWait(window); } private static WindowBasedTextGUI obtainGui() { // Provide a concrete TextGUI in your application return null; } } ``` -------------------------------- ### Start and Prepare the Screen Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial03.md Call startScreen() to prepare and set up the terminal before making any changes visible. The cursor is turned off using setCursorPosition(null). ```java screen.startScreen(); screen.setCursorPosition(null); ``` -------------------------------- ### Create Windows with Specific Hints Source: https://context7.com/mabe02/lanterna/llms.txt Use `Window.Hint` values to configure window placement, modality, and decoration. This example shows how to create a centered, modal dialog and a full-screen window. ```java import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import java.util.Arrays; public class WindowHintsDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); // Centered, modal window with no shadow BasicWindow dialog = new BasicWindow("Centered Dialog"); dialog.setHints(Arrays.asList( Window.Hint.CENTERED, Window.Hint.MODAL, Window.Hint.NO_POST_RENDERING // no shadow )); Panel content = new Panel(new LinearLayout(Direction.VERTICAL)); content.addComponent(new Label("This dialog is centered and modal.")); content.addComponent(new Button("OK", dialog::close)); dialog.setComponent(content); // Full-screen window without decorations BasicWindow fullScreen = new BasicWindow(); fullScreen.setHints(Arrays.asList(Window.Hint.FULL_SCREEN, Window.Hint.NO_DECORATIONS)); fullScreen.setComponent(new Label("Full screen content")); gui.addWindowAndWait(dialog); // show centered dialog first screen.stopScreen(); } } ``` -------------------------------- ### Instantiate WindowBasedTextGUI Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideStartTheGUI.md To instantiate `WindowBasedTextGUI`, you need a `Screen` object that the GUI will render to. This example shows the basic instantiation. ```java WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); ``` -------------------------------- ### Create Menu Bar with File and Help Menus Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/menus.md This example demonstrates how to create a menu bar with two menus, 'File' and 'Help', each containing multiple menu items with associated actions. It shows adding menu items with labels and Runnable actions, and how to integrate the menu bar into a basic window. ```java MenuBar menubar = new MenuBar(); // "File" menu Menu menuFile = new Menu("File"); menubar.addMenu(menuFile); menuFile.addMenuItem("Open...", new Runnable() { public void run() { File file = new FileDialogBuilder().build().showDialog(textGUI); if (file != null) MessageDialog.showMessageDialog( textGUI, "Open", "Selected file:\n" + file, MessageDialogButton.OK); } }); menuFile.addMenuItem("Exit", new Runnable() { public void run() { System.exit(0); } }); // "Help" menu Menu menuHelp = new Menu("Help"); menubar.addMenu(menuHelp); menuHelp.addMenuItem("Homepage", new Runnable() { public void run() { MessageDialog.showMessageDialog( textGUI, "Homepage", "https://github.com/mabe02/lanterna", MessageDialogButton.OK); } }); menuHelp.addMenuItem("About", new Runnable() { public void run() { MessageDialog.showMessageDialog( textGUI, "About", "Lanterna drop-down menu", MessageDialogButton.OK); } }); // Create window to hold the panel BasicWindow window = new BasicWindow(); window.setComponent(menubar); textGUI.addWindow(window); ``` -------------------------------- ### ActionListBox Basic Example Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates creating and populating an ActionListBox with actions. Ensure long-running actions are executed on background threads to maintain UI responsiveness. ```java TerminalSize size = new TerminalSize(20, 8); ActionListBox list = new ActionListBox(size); list.addItem("Open", () -> doOpen()); list.addItem("Save", () -> doSave()); list.addItem("Quit", () -> System.exit(0)); Panel panel = new Panel(); panel.addComponent(list.withBorder(Borders.singleLine("Actions"))); window.setComponent(panel); textGUI.addWindowAndWait(window); ``` -------------------------------- ### Create and Populate a Table Component in Java Source: https://context7.com/mabe02/lanterna/llms.txt Demonstrates how to create a scrollable, navigable `Table` component with custom data, set viewport size, and handle row selection. Includes an example of dynamically adding rows via a button. ```java import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.gui2.table.Table; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; public class TableDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); Table table = new Table<>("ID", "Name", "Status"); table.getTableModel().addRow("1", "Alpha", "Running"); table.getTableModel().addRow("2", "Beta", "Stopped"); table.getTableModel().addRow("3", "Gamma", "Queued"); table.getTableModel().addRow("4", "Delta", "Running"); table.getTableModel().addRow("5", "Epsilon","Stopped"); table.setVisibleRows(4); // viewport hint table.setCellSelection(false); // row-level selection (default) table.setSelectAction(() -> { int row = table.getSelectedRow(); System.out.println("Selected: " + table.getTableModel().getRow(row)); }); // Dynamically add a row from a button Panel panel = new Panel(new LinearLayout(Direction.VERTICAL)); panel.addComponent(table.withBorder(Borders.singleLine("Processes"))); panel.addComponent(new Button("Add Row", () -> table.getTableModel().addRow( String.valueOf(table.getTableModel().getRowCount() + 1), "New Process", "Pending"))); BasicWindow window = new BasicWindow("Table Demo"); window.setComponent(panel); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Show Directory Dialog on Button Click Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/dir_dialogs.md This example demonstrates how to display a directory dialog when a button is clicked. The selected directory's path is printed to standard output. ```java panel.addComponent(new Button("Test", new Runnable() { @Override public void run() { File input = new DirectoryDialogBuilder() .setTitle("Select directory") .setDescription("Choose a directory") .setActionLabel("Select") .build() .showDialog(textGUI); System.out.println(input); } })); ``` -------------------------------- ### Show Message Dialog on Button Click Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/message_dialogs.md This example demonstrates how to display a message dialog when a button is clicked. Ensure `textGUI` is initialized before use. ```java panel.addComponent(new Button("Test", new Runnable() { @Override public void run() { MessageDialog.showMessageDialog(textGUI, "test", "test"); } })); ``` -------------------------------- ### Create Terminal Instance Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial02.md Initializes the default terminal factory and creates a terminal instance. This is the starting point for interacting with the terminal. ```java DefaultTerminalFactory defaultTerminalFactory = new DefaultTerminalFactory(); Terminal terminal = null; try { terminal = defaultTerminalFactory.createTerminal(); ``` -------------------------------- ### Start and Stop the Screen Source: https://github.com/mabe02/lanterna/blob/master/docs/using-screen.md Before using the Screen layer, it must be started. Similarly, stop the screen when your application no longer needs it. This manages the screen's active state. ```java screen.startScreen(); // do text GUI application logic here until done screen.stopScreen(); ``` -------------------------------- ### Manage CheckBox State and Label Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Provides examples for reading and setting the checked state of a CheckBox, as well as getting and modifying its label. `setChecked(...)` updates the UI and notifies listeners. ```java // Read state: cb.isChecked() // Set state: cb.setChecked(true /* or false */) // Read/modify label: cb.getLabel(), cb.setLabel("New label") ``` -------------------------------- ### TextBox Demo: Input Fields and Validation in Lanterna Source: https://context7.com/mabe02/lanterna/llms.txt This example demonstrates creating and configuring various TextBox components, including single-line, password-masked, and validated input fields. It also shows how to set up a multi-line text area with scrollbars and a change listener. ```java import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import java.util.regex.Pattern; public class TextBoxDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); Panel panel = new Panel(new GridLayout(2)); BasicWindow window = new BasicWindow("TextBox Demo"); // Single-line text box panel.addComponent(new Label("Name:")); TextBox nameBox = new TextBox(new TerminalSize(20, 1)); panel.addComponent(nameBox); // Password field (masked input) panel.addComponent(new Label("Password:")); TextBox passBox = new TextBox(new TerminalSize(20, 1)).setMask('*'); panel.addComponent(passBox); // Digits-only validated field panel.addComponent(new Label("Age (digits):")); TextBox ageBox = new TextBox(new TerminalSize(5, 1)) .setValidationPattern(Pattern.compile("[0-9]*")); panel.addComponent(ageBox); // Multi-line text area with scrollbars and a change listener panel.addComponent(new Label("Notes:")); TextBox notes = new TextBox(new TerminalSize(30, 5), TextBox.Style.MULTI_LINE); ((TextBox.DefaultTextBoxRenderer) notes.getRenderer()).setHideScrollBars(false); notes.setTextChangeListener((text, byUser) -> { if (byUser) System.out.println("User typed: " + text.length() + " chars"); }); panel.addComponent(notes); panel.addComponent(new EmptySpace()); panel.addComponent(new Button("Submit", () -> { System.out.println("Name=" + nameBox.getText() + " Age=" + ageBox.getText()); window.close(); })); window.setComponent(panel); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Create a Terminal Instance Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/terminal/overview.md Use DefaultTerminalFactory to create a terminal instance. This is the recommended way to get a Terminal object for use with Lanterna. ```java Terminal terminal = new DefaultTerminalFactory().createTerminal(); ``` -------------------------------- ### ActionListBox Demo Source: https://context7.com/mabe02/lanterna/llms.txt Shows how to create an ActionListBox, which presents a list of actions that can be triggered by selecting an item and pressing Enter or Space. Each item is associated with a Runnable. The example includes a 'Quit' action that closes the window. ```java import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; public class ActionListBoxDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); BasicWindow window = new BasicWindow("Main Menu"); window.setHints(java.util.Arrays.asList(Window.Hint.CENTERED)); ActionListBox menu = new ActionListBox(new TerminalSize(24, 6)); menu.addItem("New File", () -> System.out.println("New File")); menu.addItem("Open File", () -> System.out.println("Open File")); menu.addItem("Save", () -> System.out.println("Save")); menu.addItem("Settings", () -> System.out.println("Settings")); menu.addItem("Quit", window::close); window.setComponent(menu.withBorder(Borders.singleLineBevel("Menu"))); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### CheckBox and CheckBoxList Demo in Lanterna Source: https://context7.com/mabe02/lanterna/llms.txt This example illustrates the use of a single CheckBox with a listener for toggle events and a CheckBoxList for managing multiple selectable options in a scrollable list. It shows how to add items, set initial states, and retrieve selected items. ```java import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import java.util.List; public class CheckBoxDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); Panel panel = new Panel(new LinearLayout(Direction.VERTICAL)); BasicWindow window = new BasicWindow("CheckBox Demo"); // Single checkbox with a state-change listener CheckBox verbose = new CheckBox("Enable verbose logging"); verbose.setChecked(true); verbose.addListener(checked -> System.out.println("Verbose: " + checked)); panel.addComponent(verbose); panel.addComponent(new Separator(Direction.HORIZONTAL)); // Multi-select list of options CheckBoxList features = new CheckBoxList<>(new TerminalSize(25, 5)); features.addItem("Dark mode", true); features.addItem("Auto-save"); features.addItem("Spell check", true); features.addItem("Notifications"); features.addListener((index, checked) -> System.out.println("Feature " + index + " -> " + checked)); panel.addComponent(features.withBorder(Borders.singleLine("Features"))); panel.addComponent(new Button("Apply", () -> { List selected = features.getCheckedItems(); System.out.println("Selected: " + selected); window.close(); })); window.setComponent(panel); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### ProgressBar with Large Renderer and Formatted Label Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Provides an example of creating and updating a ProgressBar. It configures the large renderer, a percentage label format, and updates the progress value using a timer. ```java // Create a window with a progress bar that advances over time final ProgressBar progressBar = new ProgressBar(0, 100, 24); progressBar.setRenderer(new ProgressBar.LargeProgressBarRenderer()); progressBar.setLabelFormat("%2.0f%%"); // centered percentage label Panel panel = new Panel(); panel.addComponent(progressBar.withBorder(Borders.singleLine("Progress"))); // Update from a timer/background thread Timer timer = new Timer("ProgressBarTimer", true); timer.scheduleAtFixedRate(new TimerTask() { @Override public void run() { if (progressBar.getValue() >= progressBar.getMax()) { progressBar.setValue(progressBar.getMin()); } else { progressBar.setValue(progressBar.getValue() + 1); } } }, 0, 100); Window window = new BasicWindow("Demo"); window.setComponent(panel); textGUI.addWindowAndWait(window); ``` -------------------------------- ### Example ProgressBar Theme Snippet Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md This theme snippet demonstrates how to customize the appearance of a ProgressBar, including foreground, background, SGR attributes, and specific characters for different states like ACTIVE and PRELIGHT. It also shows how to set the default renderer. ```properties # ProgressBar com.googlecode.lanterna.gui2.ProgressBar.foreground = white com.googlecode.lanterna.gui2.ProgressBar.background = blue com.googlecode.lanterna.gui2.ProgressBar.sgr = bold com.googlecode.lanterna.gui2.ProgressBar.background[ACTIVE] = red com.googlecode.lanterna.gui2.ProgressBar.foreground[PRELIGHT] = red com.googlecode.lanterna.gui2.ProgressBar.char[FILLER] = # Optional: choose the large renderer by default com.googlecode.lanterna.gui2.ProgressBar.renderer = com.googlecode.lanterna.gui2.ProgressBar$LargeProgressBarRenderer ``` -------------------------------- ### Arrange Components with Layout Managers Source: https://context7.com/mabe02/lanterna/llms.txt Utilize `Panel` with layout managers like `LinearLayout` and `GridLayout` to arrange GUI components. This example demonstrates a form using `GridLayout` and a toolbar using `LinearLayout`. ```java import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; public class LayoutDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); // GridLayout: 2-column form Panel form = new Panel(new GridLayout(2)); ((GridLayout) form.getLayoutManager()).setHorizontalSpacing(2); form.addComponent(new Label("Name:")); form.addComponent(new TextBox()); form.addComponent(new Label("Email:")); form.addComponent(new TextBox()); // Span a separator across both columns form.addComponent(new Separator(Direction.HORIZONTAL) .setLayoutData(GridLayout.createHorizontallyFilledLayoutData(2))); // Center-aligned button spanning both columns form.addComponent(new EmptySpace() .setLayoutData(GridLayout.createHorizontallyFilledLayoutData(2))); form.addComponent(new Button("Submit") .setLayoutData(GridLayout.createLayoutData( GridLayout.Alignment.CENTER, GridLayout.Alignment.CENTER, true, false, 2, 1))); // Horizontal toolbar using LinearLayout Panel toolbar = new Panel(new LinearLayout(Direction.HORIZONTAL)); toolbar.addComponent(new Button("New")); toolbar.addComponent(new Button("Open")); toolbar.addComponent(new Button("Save")); // Combine with a vertical panel Panel root = new Panel(new LinearLayout(Direction.VERTICAL)); root.addComponent(toolbar.withBorder(Borders.singleLine("Toolbar"))); root.addComponent(form.withBorder(Borders.doubleLine("Form"))); BasicWindow window = new BasicWindow("Layout Demo"); window.setComponent(root); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Create a Basic Window Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/windows.md Sets up the terminal and screen, creates a basic window, and adds it to the GUI. This is the foundational step for displaying any window. ```java // Setup terminal and screen layers Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // Create window to hold the panel BasicWindow window = new BasicWindow(); // Create gui and start gui MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLUE)); gui.addWindowAndWait(window); ``` -------------------------------- ### Get Terminal Size and Position Cursor Source: https://github.com/mabe02/lanterna/blob/master/docs/using-terminal.md Retrieve the current dimensions of the terminal (columns and rows) and use this information to position the cursor, for example, in the bottom-right corner. ```java TerminalSize screenSize = terminal.getTerminalSize(); //Place the cursor in the bottom right corner terminal.setCursorPosition(screenSize.getColumns() - 1, screenSize.getRows() - 1); ``` -------------------------------- ### Get and Set TextBox Content Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Retrieve the current text, get text with a default value if empty, or set new text programmatically. ```java tb.setText("New text"); String text = tb.getText(); String valueOrDefault = tb.getTextOrDefault(""); ``` -------------------------------- ### Basic Window Management in Lanterna Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/basic_form_submission.md Demonstrates how to initialize a MultiWindowTextGUI and add a window to it. This is a fundamental step for creating multi-window applications. ```java MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLUE)); gui.addWindowAndWait(window); } } ``` -------------------------------- ### Core API: Content Management Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Methods for getting, setting, and retrieving text content from a TextBox. ```APIDOC ## Core API: Content Management ### Description Provides methods to interact with the text content of a TextBox. ### Methods - `setText(String newText)`: Sets the entire text content of the TextBox. - `getText()`: Returns the current text content of the TextBox. - `getTextOrDefault(String defaultValue)`: Returns the current text content or a default value if the TextBox is empty. ``` -------------------------------- ### Get Selected Index Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/combo_boxes.md Retrieves the index of the currently selected item in the ComboBox. Returns an integer. ```java // Returns an integer value comboBox.getSelectedIndex(); ``` -------------------------------- ### Create a Full Screen Window Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/windows.md Creates a basic window and applies the FULL_SCREEN hint to make it occupy the entire terminal screen. ```java BasicWindow window = new BasicWindow(); window.setHints(Arrays.asList(Window.Hint.FULL_SCREEN)); ``` -------------------------------- ### Get Checked Item from Radio Box List Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/radio_boxes.md Retrieve the currently selected item from the radio box list. ```java String checkedItems = radioBoxList.getCheckedItem(); ``` -------------------------------- ### Create and Configure a Tree Component in Java Source: https://context7.com/mabe02/lanterna/llms.txt Illustrates the creation of a hierarchical `Tree` component from a `TreeNode` structure. Shows how to customize display options like hiding the root node and enabling navigation wrapping. ```java import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.gui2.Tree; import com.googlecode.lanterna.gui2.TreeNode; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; public class TreeDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); WindowBasedTextGUI gui = new MultiWindowTextGUI(screen); // Build the tree model TreeNode root = new TreeNode<>("root", true); TreeNode src = root.addChild("src", true); TreeNode main = src.addChild("main", true); main.addChild("App.java", true); main.addChild("Config.java", true); TreeNode test = src.addChild("test", false); // collapsed test.addChild("AppTest.java", true); root.addChild("pom.xml", true); root.addChild("README.md", true); Tree tree = new Tree<>(root, 30, 10); tree.setDisplayRoot(false); // hide "root" label; start from children tree.setOverflowCircle(true); // wrap navigation at top/bottom tree.setNodeSelectedConsumer(node -> System.out.println("Activated: " + node.getLabel())); BasicWindow window = new BasicWindow("Project Tree"); window.setComponent(tree.withBorder(Borders.singleLine("Files"))); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Get Selected Items from CheckBoxList Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/check_boxes.md Retrieves a list of all items that have been checked by the user. This is useful for processing user selections. ```java List checkedItems = checkBoxList.getCheckedItems(); ``` -------------------------------- ### Create Buttons with Initial Actions Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates creating Button instances with and without an initial action (Runnable). The Runnable is executed when the button is triggered. ```java import com.googlecode.lanterna.gui2.Button; public class ButtonCreateExample { void demo() { // No action initially; add listeners later Button b1 = new Button("OK"); // With an initial action (Runnable) that runs when the button is triggered Button b2 = new Button("Save", () -> doSave()); } private void doSave() { // ... } } ``` -------------------------------- ### Basic GUI Window with Lanterna Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/hello_world.md This code sets up a basic GUI window with labels, text boxes, and a submit button. It requires importing necessary Lanterna classes for terminal, screen, GUI components, and layout management. Ensure the terminal and screen are properly initialized and closed. ```java import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.screen.TerminalScreen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import com.googlecode.lanterna.terminal.Terminal; import java.io.IOException; public class HelloWorld { public static void main(String[] args) throws IOException { // Setup terminal and screen layers Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // Create panel to hold components Panel panel = new Panel(); panel.setLayoutManager(new GridLayout(2)); panel.addComponent(new Label("Forename")); panel.addComponent(new TextBox()); panel.addComponent(new Label("Surname")); panel.addComponent(new TextBox()); panel.addComponent(new EmptySpace(new TerminalSize(0,0))); // Empty space underneath labels panel.addComponent(new Button("Submit")); // Create window to hold the panel BasicWindow window = new BasicWindow(); window.setComponent(panel); // Create gui and start gui MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLUE)); gui.addWindowAndWait(window); } } ``` -------------------------------- ### TextBox Creation Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates various ways to create a TextBox instance, from empty to pre-filled with specific styles and sizes. ```APIDOC ## TextBox Creation ### Description Examples of creating TextBox instances with different configurations. ### Code Examples - Empty single-line with default size (10x1): ```java TextBox tb = new TextBox(); ``` - From initial content, auto-detecting style (multi-line if it contains `\n`): ```java TextBox tb = new TextBox("Hello World"); TextBox multi = new TextBox("Line 1\nLine 2"); ``` - With explicit size and/or style: ```java TextBox fixed = new TextBox(new TerminalSize(20, 1)); // single-line (rows == 1) TextBox area = new TextBox(new TerminalSize(30, 8), TextBox.Style.MULTI_LINE); TextBox sizedFromText = new TextBox(null, "Prefill", TextBox.Style.SINGLE_LINE); ``` ``` -------------------------------- ### Panel with Border Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Wrap any component, including a Panel, with a border using the `withBorder` helper. This example adds a single-line border with a title. ```java Panel borderedPanel = panel.withBorder(Borders.singleLine("Title")); ``` -------------------------------- ### Using CheckBoxList in a Layout Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md An example of integrating a CheckBoxList component within a vertical LinearLayout inside a Panel, including adding items and applying a border. ```Java Panel panel = new Panel(); panel.setLayoutManager(new LinearLayout(Direction.VERTICAL)); CheckBoxList features = new CheckBoxList<>(new TerminalSize(24, 6)); features.addItem("Logging", true); features.addItem("Metrics"); features.addItem("Tracing"); panel.addComponent(features.withBorder(Borders.singleLine("Features"))); ``` -------------------------------- ### Basic Table Usage Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Create a table with specified columns, add rows, and optionally configure selection mode, visible area, and activation actions. Add the table to a Panel for display. ```java Table table = new Table<>("ID", "Name", "Status"); table.getTableModel().addRow("1", "Alpha", "Running"); table.getTableModel().addRow("2", "Beta", "Stopped"); table.getTableModel().addRow("3", "Gamma", "Queued"); // Optional: choose selection mode (row selection by default) table.setCellSelection(false); // set to true to allow Left/Right to move between cells // Optional: limit the visible area (viewport hint) table.setVisibleRows(10); table.setVisibleColumns(3); // Optional: provide an activation action (Enter/Space or mouse selection) table.setSelectAction(() -> { int row = table.getSelectedRow(); int col = table.isCellSelection() ? table.getSelectedColumn() : -1; List currentRow = table.getTableModel().getRow(row); System.out.println("Activated row=" + row + ", col=" + col + ", data=" + currentRow); }); // Add to a container and display in a WindowBasedTextGUI Panel container = new Panel(); container.addComponent(table); ``` ```java Panel p = new Panel(); p.setPreferredSize(new TerminalSize(40, 12)); p.addComponent(table); ``` -------------------------------- ### Create a Table with Headers Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/tables.md Initializes a new table with specified column headers. The number of arguments must match the desired number of columns. ```java Table table = new Table("Column 1", "Column 2", "Column 3"); ``` -------------------------------- ### Create a Button to Close the Window Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideWindows.md Add a Button component that executes a Runnable action when activated. This example demonstrates a button that closes the current window. ```java public class MyWindow extends BasicWindow { public MyWindow() { super("My Window!"); setComponent(new Button("Exit", new Runnable() { @Override public void run() { MyWindow.this.close(); } })); } } ``` -------------------------------- ### Basic RadioBoxList Initialization and Usage Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Demonstrates how to create a RadioBoxList, add items, set a checked item, and retrieve the currently checked item. ```java TerminalSize size = new TerminalSize(14, 6); RadioBoxList radio = new RadioBoxList<>(size); radio.addItem("Small"); radio.addItem("Medium"); radio.addItem("Large"); radio.setCheckedItem("Medium"); // Later String choice = radio.getCheckedItem(); ``` -------------------------------- ### Create a Simple Label Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/labels.md Instantiate a Label with the desired text. ```java Label label = new Label("Here is a label"); ``` -------------------------------- ### AnimatedLabel Classic Spinner Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Creates a classic spinning line animation. The animation starts immediately with a default frame rate. Call stopAnimation() when the operation completes. ```java // Create a classic spinner and start it immediately (default ~150 ms between frames) AnimatedLabel spinner = AnimatedLabel.createClassicSpinningLine(); // Add to your layout Panel content = new Panel(); content.addComponent(spinner); // ... later, when the operation finishes spinner.stopAnimation(); ``` -------------------------------- ### Custom RadioBoxList Item Rendering Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Implement a custom ListItemRenderer to control how each item in a RadioBoxList is displayed. This example shows how to customize the checked/unchecked indicator and the label text. ```java radio.setListItemRenderer(new ListItemRenderer>() { @Override public int getHotSpotPositionOnLine(int selectedIndex) { return 1; // position of the marker hot-spot if you keep a marker } @Override public String getLabel(RadioBoxList listBox, int index, String item) { boolean checked = listBox.getCheckedItemIndex() == index; return (checked ? "(x) " : "( ) ") + item; } @Override public void drawItem(TextGUIGraphics g, RadioBoxList list, int index, String item, boolean selected, boolean focused) { // You can delegate most work to default styles ThemeDefinition def = list.getTheme().getDefinition(RadioBoxList.class); ThemeStyle style = selected ? (focused ? def.getActive() : def.getSelected()) : (focused ? def.getInsensitive() : def.getNormal()); g.applyThemeStyle(style); g.fill(' '); g.putString(0, 0, getLabel(list, index, item)); } }); ``` -------------------------------- ### Create a Basic Window Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial04.md Instantiates a new window with an optional title. This window will serve as a container for other components. ```java final Window window = new BasicWindow("My Root Window"); ``` -------------------------------- ### Handle terminal resize Source: https://github.com/mabe02/lanterna/blob/master/docs/using-screen.md Call doResizeIfNecessary() at the start of your drawing loop to check for terminal size changes. If the size has changed, it updates the buffer dimensions and returns the new size. ```java TerminalSize newSize = screen.doResizeIfNecessary(); if(newSize != null) { terminalSize = newSize; } ``` -------------------------------- ### Create a CheckBoxList Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Illustrates how to create a `CheckBoxList` component, optionally specifying a preferred size. If no size is provided, it grows to fit its items. ```java TerminalSize size = new TerminalSize(20, 8); // optional preferred size CheckBoxList list = new CheckBoxList<>(size); ``` ```java // Without preferred size (grows to fit items): // CheckBoxList list = new CheckBoxList<>(); ``` -------------------------------- ### Manage TextBox Lines (Multi-line) Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Useful for multi-line TextBoxes, these methods allow getting the line count, accessing specific lines, adding new lines, and removing existing ones. ```java int lines = tb.getLineCount(); String first = tb.getLine(0); tb.addLine("Another line"); tb.removeLine(1); ``` -------------------------------- ### Label Foreground and Background Colors Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Override default foreground and background colors for a Label. Set to `null` to revert to theme defaults. This example sets the text to red on a black background. ```java Label styled = new Label("Important"); styled .setForegroundColor(TextColor.ANSI.RED) .setBackgroundColor(TextColor.ANSI.BLACK) .addStyle(SGR.BOLD) .addStyle(SGR.UNDERLINE); ``` -------------------------------- ### Creating a ComboBox with Initial Text and Items Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Creates a ComboBox with placeholder text and a list of items. The initial text is displayed until the user makes a selection or types. ```Java ComboBox combo = new ComboBox<>("Type here…", List.of("Item 1", "Item 2")); // getSelectedIndex() will return -1 initially ``` -------------------------------- ### Panel Background Fill Override Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Override the default background fill color for a Panel. Set to `null` to use the theme's default background. This example fills the panel with a blue background. ```java panel.setFillColorOverride(TextColor.ANSI.BLUE); ``` -------------------------------- ### Basic Terminal Layer Demo in Java Source: https://context7.com/mabe02/lanterna/llms.txt Demonstrates basic terminal manipulation using Lanterna's Terminal layer. This includes entering private mode, clearing the screen, setting colors, positioning the cursor, writing text, and enabling SGR modifiers. Remember to call flush() to make changes visible and exit private mode before closing. ```java import com.googlecode.lanterna.SGR; import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import com.googlecode.lanterna.terminal.Terminal; public class TerminalDemo { public static void main(String[] args) throws Exception { // Auto-detect: SwingTerminalFrame in GUI env, UnixTerminal otherwise Terminal terminal = new DefaultTerminalFactory().createTerminal(); terminal.enterPrivateMode(); // fullscreen buffer, no scrollback terminal.clearScreen(); terminal.setCursorVisible(false); // Set colors and print text character-by-character terminal.setForegroundColor(TextColor.ANSI.YELLOW); terminal.setBackgroundColor(TextColor.ANSI.BLUE); terminal.setCursorPosition(5, 3); for (char c : "Hello, Lanterna!".toCharArray()) { terminal.putCharacter(c); } // Bold SGR modifier terminal.enableSGR(SGR.BOLD); terminal.setCursorPosition(5, 4); for (char c : "Bold text".toCharArray()) terminal.putCharacter(c); terminal.resetColorAndSGR(); terminal.flush(); // must call flush() to make changes visible Thread.sleep(3000); terminal.exitPrivateMode(); terminal.close(); } } ``` -------------------------------- ### Apply Global and Per-Component Themes with SimpleTheme Source: https://context7.com/mabe02/lanterna/llms.txt This Java code demonstrates how to create and apply a global theme to a Lanterna GUI, and also how to override the theme for a specific component. It sets up a basic window with labels and buttons, applying a cyan-on-black theme globally and a custom red theme to an alert label. ```java import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.gui2.*; import com.googlecode.lanterna.gui2.dialogs.MessageDialog; import com.googlecode.lanterna.gui2.dialogs.MessageDialogButton; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; public class ThemeDemo { public static void main(String[] args) throws Exception { Screen screen = new DefaultTerminalFactory().createScreen(); screen.startScreen(); // Global theme: dark background, cyan foreground SimpleTheme theme = new SimpleTheme(TextColor.ANSI.CYAN, TextColor.ANSI.BLACK); theme.getDefaultDefinition().setActive(TextColor.ANSI.BLACK, TextColor.ANSI.CYAN); MultiWindowTextGUI gui = new MultiWindowTextGUI(screen); gui.setTheme(theme); BasicWindow window = new BasicWindow("Themed Window"); Panel panel = new Panel(new LinearLayout(Direction.VERTICAL)); panel.addComponent(new Label("Themed label in cyan-on-black")); panel.addComponent(new Button("Themed button", window::close)); // Per-component theme override SimpleTheme redTheme = SimpleTheme.makeTheme(false, TextColor.ANSI.WHITE, TextColor.ANSI.RED, TextColor.ANSI.WHITE, TextColor.ANSI.RED, TextColor.ANSI.WHITE, TextColor.ANSI.RED, TextColor.ANSI.WHITE); Label alert = new Label("ALERT: custom red theme"); alert.setTheme(redTheme); panel.addComponent(alert); window.setComponent(panel); gui.addWindowAndWait(window); screen.stopScreen(); } } ``` -------------------------------- ### Create TextBox Instances Source: https://github.com/mabe02/lanterna/blob/master/docs/GUIGuideComponents.md Instantiate TextBox with default settings, initial content, or explicit size and style. Multi-line style is inferred if rows > 1 or content contains '\n'. ```java TextBox tb = new TextBox(); ``` ```java TextBox tb = new TextBox("Hello World"); TextBox multi = new TextBox("Line 1\nLine 2"); ``` ```java TextBox fixed = new TextBox(new TerminalSize(20, 1)); // single-line (rows == 1) TextBox area = new TextBox(new TerminalSize(30, 8), TextBox.Style.MULTI_LINE); TextBox sizedFromText = new TextBox(null, "Prefill", TextBox.Style.SINGLE_LINE); ``` -------------------------------- ### Simple Calculator GUI Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/basic_form_submission.md Sets up a basic calculator with two number input fields and an 'Add' button. The result is displayed in a label. Input fields are validated to accept only numbers. ```java package com.googlecode.lanterna.gui2; import com.googlecode.lanterna.TerminalSize; import com.googlecode.lanterna.TextColor; import com.googlecode.lanterna.screen.Screen; import com.googlecode.lanterna.screen.TerminalScreen; import com.googlecode.lanterna.terminal.DefaultTerminalFactory; import com.googlecode.lanterna.terminal.Terminal; import java.io.IOException; import java.util.regex.Pattern; public class Calculator { public static void main(String[] args) throws IOException { // Setup terminal and screen layers Terminal terminal = new DefaultTerminalFactory().createTerminal(); Screen screen = new TerminalScreen(terminal); screen.startScreen(); // Create panel to hold components Panel panel = new Panel(); panel.setLayoutManager(new GridLayout(2)); final Label lblOutput = new Label(""); panel.addComponent(new Label("Num 1")); final TextBox txtNum1 = new TextBox().setValidationPattern(Pattern.compile("[0-9]*")).addTo(panel); panel.addComponent(new Label("Num 2")); final TextBox txtNum2 = new TextBox().setValidationPattern(Pattern.compile("[0-9]*")).addTo(panel); panel.addComponent(new EmptySpace(new TerminalSize(0, 0))); new Button("Add!", new Runnable() { @Override public void run() { int num1 = Integer.parseInt(txtNum1.getText()); int num2 = Integer.parseInt(txtNum2.getText()); lblOutput.setText(Integer.toString(num1 + num2)); } }).addTo(panel); panel.addComponent(new EmptySpace(new TerminalSize(0, 0))); panel.addComponent(lblOutput); // Create window to hold the panel BasicWindow window = new BasicWindow(); window.setComponent(panel); // Create gui and start gui MultiWindowTextGUI gui = new MultiWindowTextGUI(screen, new DefaultWindowManager(), new EmptySpace(TextColor.ANSI.BLUE)); gui.addWindowAndWait(window); } } ``` -------------------------------- ### Set Grid Layout Manager with Two Columns Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/layout_managers.md Use GridLayout with a specified number of columns to arrange components in a grid. Components are added from left to right, starting a new row when the column count is reached. An `EmptySpace` can be used to fill cells. ```java // Grid will have two columns panel.setLayoutManager(new GridLayout(2)); // As this grid is a 2xN grid, each row must have 2 elements. // An empty space is added before the button to fill in the cell before the buttons cell. buttonPanel.addComponent(new EmptySpace(new TerminalSize(0, 0))); buttonPanel.addComponent(new Button("Enter")); ``` -------------------------------- ### Initialize MultiWindowTextGUI Source: https://github.com/mabe02/lanterna/blob/master/docs/tutorial/Tutorial04.md Creates an instance of the MultiWindowTextGUI using the initialized screen. By default, this uses the calling thread for UI operations and sets a solid blue background. ```java final WindowBasedTextGUI textGUI = new MultiWindowTextGUI(screen); ``` -------------------------------- ### Create an Action List Box Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/action_list_box.md Initializes a new ActionListBox with a specified terminal size. This is the first step to creating an interactive list of actions. ```java TerminalSize size = new TerminalSize(14, 10); ActionListBox actionListBox = new ActionListBox(size); ``` -------------------------------- ### Create and Show an Action List Dialog Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/action_list_dialogs.md Builds and displays an action list dialog with multiple selectable items. Each action is associated with a Runnable task to be executed upon selection. ```java new ActionListDialogBuilder() .setTitle("Action List Dialog") .setDescription("Choose an item") .addAction("First Item", new Runnable() { @Override public void run() { // Do 1st thing... } }) .addAction("Second Item", new Runnable() { @Override public void run() { // Do 2nd thing... } }) .addAction("Third Item", new Runnable() { @Override public void run() { // Do 3rd thing... } }) .build() .showDialog(textGUI); ``` -------------------------------- ### Set Validation Pattern for Text Box Source: https://github.com/mabe02/lanterna/blob/master/docs/examples/gui/text_boxes.md Limit user input to a specific pattern using `setValidationPattern`. This example restricts input to a single digit. Input is validated on each key press, and invalid modifications are ignored. Existing content is validated on pattern set, throwing an exception if it doesn't match. ```java new TextBox().setValidationPattern(Pattern.compile("[0-9]")); ```