Search code examples
javastringuser-interfacetextboxlanterna

Java Lanterna - how can I get input from a textbox?


I'm a relatively new Java programmer (about two months experience) and I can't figure out how to get the data inputted into a Lanterna (a library for creating terminal user interfaces) textbox into a string for later use.

Here is my code:

//Variables (that I can't seem to populate)
final String usernameIn = null;
final String passwordIn = null;

//Username panel, contains Label and TextBox
Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
username.addComponent(new Label("Username: "));
username.addComponent(new TextBox(null, 15));
addComponent(username);

//Password panel, contains label and PasswordBox
Panel password = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
password.addComponent(new Label("Password: "));
password.addComponent(new PasswordBox(null, 15));
addComponent(password);

//Controls panel, contains Button w/ action
Panel controls = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
controls.addComponent(new Button("Login", new Action()
{
    public void doAction() {
        MessageBox.showMessageBox(getOwner(), "Alert", "You entered the username " + usernameIn + " and password " + passwordIn + ".");
    }
}));
addComponent(controls);

Any help would be really appreciated. I have looked all over for information but there really isn't much on Lanterna and it's the only up-to-date Java library that I could find allowing me to make terminal applications. Please note: I'm aware there's nothing in the above code that'll process the inputted data, I left out all of my attempts as they caused pages upon pages of errors (which is to be expected when using the wrong functions).


Solution

  • I got a look into the Lanterna code: TextBox has a getText() method.

    As an idea:

    Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
    username.addComponent(new Label("Username: "));
    TextBox userBox = new TextBox(null, 15);
    username.addComponent(userBox);
    addComponent(username);
    // ... and later elsewhere 
    usernameIn = userBox.getText();
    

    Shure, you need a reference to userBox to get the content later elsewhere in your code.

    Lanterna has also a ComponentListener interface to response if a value changed:

    Panel username = new Panel(new Border.Invisible(), Panel.Orientation.HORISONTAL);
    username.addComponent(new Label("Username: "));
    TextBox userBox = new TextBox(null, 15);
    userBox.addComponentListener(new ComponentListener() {
        void onComponentValueChanged(InteractableComponent component) {
             usernameIn = ((TextBox)component).getText();
        }
    });
    
    username.addComponent(userBox);
    addComponent(username);
    

    That seems even cleaner.