beryx / text-io

A library for creating interactive console applications in Java
http://text-io.beryx.org/
Apache License 2.0
342 stars 45 forks source link

Clear the console #10

Closed zygimantus closed 6 years ago

zygimantus commented 6 years ago

Is there a way or a feature to clear the console using this library? Standard way using System.out.print("\033[H\033[2J"); is not working.

siordache commented 6 years ago

Currently, the API doesn't provide a way to clear the console. I will add this feature in the next release. As a workaround, you can use the clearScreen method shown in the code below:

import org.beryx.textio.TextIO;
import org.beryx.textio.TextIoFactory;
import org.beryx.textio.TextTerminal;
import org.beryx.textio.jline.JLineTextTerminal;
import org.beryx.textio.swing.SwingTextTerminal;

public class ClearTest {
    public static void clearScreen(TextTerminal terminal) {
        if (terminal instanceof JLineTextTerminal) {
            terminal.print("\033[H\033[2J");
        } else if (terminal instanceof SwingTextTerminal) {
            ((SwingTextTerminal) terminal).resetToOffset(0);
        }
    }

    public static void main(String[] args) {
        TextIO textIO = TextIoFactory.getTextIO();
        TextTerminal terminal = textIO.getTextTerminal();

        String user = textIO.newStringInputReader().read("Username");

        clearScreen(terminal);

        int age = textIO.newIntInputReader().read("Age");

        textIO.dispose();
    }
}
zygimantus commented 6 years ago

Thank you. Your given method saves the day.