How to print to textArea instead of console in eclipse?

前端 未结 1 1987
陌清茗
陌清茗 2021-01-24 01:03

I currently have a program that prints lines of text to the screen in various manners such as \'System.out.println()\' statements and for loops the print all elements in an arra

1条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-24 01:46

    If you really want to do this, set the System OutputStream to a PipedOutputStream and connect that to a PipedInputStream that you read from to add text to your component, for example:

    PipedOutputStream pOut = new PipedOutputStream();
    System.setOut(new PrintStream(pOut));
    PipedInputStream pIn = new PipedInputStream(pOut);
    BufferedReader reader = new BufferedReader(new InputStreamReader(pIn));
    

    You can then read from the reader and write it to your text component, for example:

    while(appRunning) {
        try {
            String line = reader.readLine();
            if(line != null) {
                // Write line to component
            }
        } catch (IOException ex) {
            // Handle ex
        }
    }
    

    I'd suggest that you don't use System.out for your application output though, it can be used by anything (e.g. any third party libraries you decide to use). I'd use logging of some sort (java.util.logging, Log4J etc) with an appropriate appender to write to your component.

    0 讨论(0)
提交回复
热议问题