【问题标题】:How to print to textArea instead of console in eclipse?如何在 Eclipse 中打印到 textArea 而不是控制台?
【发布时间】:2010-10-08 13:44:24
【问题描述】:

我目前有一个程序,它以各种方式将文本行打印到屏幕上,例如“System.out.println()”语句和 for 循环将数组中的所有元素打印到屏幕上。

我现在在一个单独的类中向这个程序添加一个 GUI。我的问题是我想将打印到 Eclipse 控制台的所有内容打印到我的 GUI 中的文本框。这可能吗?如果可以,我将如何去做。

【问题讨论】:

标签: java eclipse


【解决方案1】:

如果您真的想这样做,请将 System OutputStream 设置为 PipedOutputStream 并将其连接到您从中读取的 PipedInputStream 以将文本添加到您的组件,例如:

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

然后您可以从阅读器中读取并将其写入您的文本组件,例如:

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

我建议您不要将 System.out 用于您的应用程序输出,它可以被任何东西使用(例如,您决定使用的任何第三方库)。我会使用某种类型的日志记录(java.util.logging、Log4J 等)和适当的附加程序来写入您的组件。

【讨论】:

    猜你喜欢
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 2019-08-31
    • 2020-05-17
    • 1970-01-01
    相关资源
    最近更新 更多