简体   繁体   English

在将文本从控制台重定向到JTextArea / JTextPane时需要帮助

[英]Need help on redirecting text from console to JTextArea/JTextPane

I am trying to display the console output to JTextArea/JTextPane. 我正在尝试将控制台输出显示到JTextArea / JTextPane。

MY class has several methods that has system.out.println() statements. MY类有几种具有system.out.println()语句的方法。

I have followed several examples but could not get a perfect one that suits my requirement 我遵循了几个示例,但未能找到适合我要求的完美示例

Here is my Code snippet which I have used: 这是我使用过的代码段:

private JTextArea textArea = new JTextArea(30, 30);
JScrollPane scrollPane = new JScrollPane(textArea);
private  TextAreaOutputStream taOutputStream = new TextAreaOutputStream(
            textArea, "Test");

System.setOut(new PrintStream(taOutputStream));

And my TextAreaOutPutStream is as follows: 我的TextAreaOutPutStream如下:

import java.io.IOException;
import java.io.OutputStream;

import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class TextAreaOutputStream extends OutputStream {

    private final JTextArea textArea;
    private final StringBuilder sb = new StringBuilder();
    public TextAreaOutputStream(final JTextArea textArea, String title) {
        this.textArea = textArea;
        this.title = title;
        sb.append(title + "> ");
    }

    @Override
    public void flush() {
    }

    @Override
    public void close() {
    }

    @Override
    public void write(int b) throws IOException {
    textArea.append(String.valueOf((char)b));
    textArea.setCaretPosition(textArea.getDocument().getLength());
    }
}

Now my problem is I am getting my output on jtextArea only after the entire program is completed. 现在我的问题是,只有在整个程序完成后,我才能在jtextArea上获得输出。

How can I get this printed one by one when ever the program encounters system.out.println() and print its output to JtextArea immediately. 每当程序遇到system.out.println()时如何将其一一打印出来并立即将其输出打印到JtextArea。

I have seen several examples where they have specified to use swingworker, but here how can I use that when I have several methods?? 我已经看到了几个指定使用swingworker的示例,但是在这里,当我有几种方法时该如何使用呢?

Please provide your solutions for this. 请为此提供您的解决方案。

在自动刷新模式下使用PrintStream

System.setOut(new PrintStream(taOutputStream, true));

I've tried using your code (in NetBeans) and it works perfectly fine. 我已经尝试过使用您的代码(在NetBeans中),并且效果很好。 Where is the location of the line new TextAreaOutputStream(...) ? new TextAreaOutputStream(...)的位置在哪里?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM