0

I am trying to display the console output to JTextArea/JTextPane.

MY class has several methods that has system.out.println() statements.

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:

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.

How can I get this printed one by one when ever the program encounters system.out.println() and print its output to JtextArea immediately.

I have seen several examples where they have specified to use swingworker, but here how can I use that when I have several methods??

Please provide your solutions for this.

sandy
  • 27
  • 6

2 Answers2

0

Use PrintStream in autoflushing mode

System.setOut(new PrintStream(taOutputStream, true));
anttix
  • 7,709
  • 1
  • 24
  • 25
  • Tried this but still no luck... it is getting printed only at the completion of the program – sandy Mar 18 '14 at 17:23
0

I've tried using your code (in NetBeans) and it works perfectly fine. Where is the location of the line new TextAreaOutputStream(...)?

Dame Lyngdoh
  • 312
  • 4
  • 18
  • I have used it in the constructor of the class as the first statement – sandy Mar 18 '14 at 17:33
  • How about putting: TextAreaOutputStream taOutputStream = new TextAreaOutputStream( textArea, "Test"); System.setOut(new PrintStream(taOutputStream)); at the last (if possible the end of constructor or the line where you instantiate the main/gui class, which was what I did) – Dame Lyngdoh Mar 18 '14 at 18:04
  • Still the same issue.. i have place it where i will instantiate my GUI., but still the same result – sandy Mar 18 '14 at 18:12