0

So I'm trying to redirect a textbox to System.in. I've seen this thread Redirect System.in to swing component , and seem to have everything working:

private class SystemIn extends InputStream {

    @Override
    public int read() {
        int x = GUIConsole.this.read();
        System.out.println("Read called: returning " + x);
        return x;
    }

}

The reads seem to be executing properly: I have a helper

public static String readLine(String msg) {
    String input = "";
    InputStreamReader converter = new InputStreamReader(System.in);
    BufferedReader in = new BufferedReader(converter);

    while (input.length() == 0) {
        try {
            print(msg);
            input = in.readLine().trim();
        } catch (Exception ignore) {
            //
        }
    }
    return input;
}

And I call

String in3 = SimpleConsole.readLine("Enter text: ");
System.out.println("You said: " + in3);

So the "Read called: returning #" is printed. I get the proper character codes followed by the final -1 when I call something. The read method blocks until input is ready, as the docs specify.

However, I only get the "Read called..." messages, and the next line ("You said...") never executes (it's stuck still reading). I can't for my life figure out what the problem is - If you want to see more code (although I think the "Read called..." messages show it's doing the right thing) just let me know.

Is there something else I should do to be able to call readLine and get the input from a textbox? I also tried overriding the other methods in inputstream without luck (again, the read method is executing properly)

4

1 回答 1

1

啊,像往常一样,我在发布问题后很快就找到了答案(我也每次都这么说)。无论如何,如果其他人正在寻找这个:

读取/实现输入流时,请确保最后一次调用返回换行符 \n'(后跟 -1)。因为如果你是 readline一行,它会等待最后一个换行符。

所以对我来说,我将文本字段中的文本加上换行符。现在它可以工作了,程序完成读取和打印最终消息。

于 2013-05-05T06:11:42.567 回答