I\'m trying to get the content of console in a textArea in java.
For example if we have this code,
class FirstApp {
public static void main (Stri
I found this simple solution:
First, you have to create a class to replace the standard output:
public class CustomOutputStream extends OutputStream {
private JTextArea textArea;
public CustomOutputStream(JTextArea textArea) {
this.textArea = textArea;
}
@Override
public void write(int b) throws IOException {
// redirects data to the text area
textArea.append(String.valueOf((char)b));
// scrolls the text area to the end of data
textArea.setCaretPosition(textArea.getDocument().getLength());
// keeps the textArea up to date
textArea.update(textArea.getGraphics());
}
}
Then you replace standards as follows:
JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);
The problem is that all the outputs will be showed only in the text area.
Source with a sample: http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea
One of the way you can do it by setting the System OutputStream
to a PipedOutputStream
and connect that to a PipedInputStream
that you read from to add text to your component, E.g
PipedOutputStream pOut = new PipedOutputStream();
System.setOut(new PrintStream(pOut));
PipedInputStream pIn = new PipedInputStream(pOut);
BufferedReader reader = new BufferedReader(new InputStreamReader(pIn));
Have u looked at the following link ? If not, then you must.
like this http://img122.imageshack.us/img122/5692/dibujoof2.png
Create Java console inside a GUI panel
You'll have to redirect System.out
to a custom, observable subclass of PrintStream
, so that each char or line added to that stream can update the content of the textArea (I guess, this is an AWT or Swing component)
The PrintStream
instance could be created with a ByteArrayOutputStream
, which would collect the output of the redirected System.out
Message Console shows one solution for this.