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 が続く) を返すことを確認してください。を読み込んでいる場合、最後の改行を待つからです。

したがって、私は、テキストフィールド改行文字からテキストを追加します。これで動作し、プログラムは最終メッセージの読み取りと出力を終了します。

于 2013-05-05T06:11:42.567 に答える