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)

Community
  • 1
  • 1
Raekye
  • 4,795
  • 8
  • 45
  • 72

1 Answers1

1

Agh, as usual, I find the answer soon after I post a question (and I say this every time too). Anyways, in case someone else is looking for this:

When reading/implementing the inputstream, make sure the last call returns the newline char \n' (followed by -1). Because if you're readline a line it waits for that last newline feed.

So for me, I append the text from a textfield plus a newline character. Now it works, the program finishes reading and printing the final message.

Raekye
  • 4,795
  • 8
  • 45
  • 72