Java控制台输出重叠扫描仪



我正在尝试创建一个控制台输入系统,同时可以打印输出:

new Thread(() ->{ //asynchronous output test every 2 sec
        while(true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            System.out.println("test");
        }
    }).start();

这就是我获得用户输入的方式:

String line = scanner.nextLine();

但是,当我输入并且同时出现输出时,这就是结果:

Test
Test
TestI'm try
Testing to type

有没有办法在控制台底部显示输入线?

解决方案是每次键入和存储实际写入变量中的内容时获取输入。然后,在编写"测试"之前,通过在控制台中几次打印b来清除用户输入的字符量。之后,您可以再次打印用户的输入,以使其感觉像"测试"只是在上方打印出来。

棘手的部分是像他类型一样获取用户的输入。我使用Jline lib来实现这一目标。我还确保"测试"打印线程以同步的方式获得了线程安全性的输入线。

private static String inputLine = "";
synchronized static String getInputLine() {
    return inputLine;
}
synchronized static void setInputLine(String line) {
    inputLine = line;
}
public static void main(String[] args) {
    char c;
    char allowed[] = {'a','b','c','d','e','f','g','h','i','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','n','r','b'};
    ConsoleReader reader;
    PrintWriter out = new PrintWriter(System.out);
    new Thread(() ->{ //Asynchronous output test every 2 sec
        while(true) {
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            String erase = ""; //Prepare a string as long as the input made b characters
            for(int i = 0 ; i < getInputLine().length() ; i++)
                erase += 'b';
            String whitespace = ""; //Prepare a string of whitespaces to override the characters after "test" (thus -4)  
            for(int i = 0 ; i < getInputLine().length() - 4 ; i++)
                whitespace += ' ';
            out.print(erase); //Erase the input line                
            out.println("test" + whitespace);
            out.print(getInputLine());
            out.flush();
        }
    }).start();
    try {
        reader = new ConsoleReader();
        reader.setBellEnabled(false);
        while(true){
            c = (char) reader.readCharacter(allowed);
            if(c == 'r' || c == 'n') {
                //Do something with the input
                setInputLine("");
                out.println();
            } else if(c == 'b') { //Backspace
                String line = getInputLine();
                setInputLine(line.substring(0, line.length()-1));
                out.print(c);
                out.print(" "); //Print whitespace to erase trailing char
                out.print(c); //Backspace again to send the carret back to the last char
            } else {
                setInputLine(getInputLine() + c);
                out.print(c);
            }
            out.flush();
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

这个程序对我有用,但仅在我的IDE之外。请注意,该程序被卡在无限的循环中,因此,如果要将其关闭,则必须使用"退出"命令从代码中处理它。

编辑:还以同步方式设置输入线。

最新更新