redirect System Streams to JTextArea - Java java.lang

Java examples for java.lang:System

Description

redirect System Streams to JTextArea

Demo Code


//package com.java2s;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;

public class Main {
    public static void redirectSystemStreams(final JTextArea textArea) {
        OutputStream out = new OutputStream() {

            @Override/*  w  w w . j a  va  2s . co  m*/
            public void write(int b) throws IOException {
                updateTextArea(textArea, String.valueOf((char) b));
            }

            @Override
            public void write(byte[] b, int off, int len)
                    throws IOException {
                updateTextArea(textArea, new String(b, off, len));
            }

            @Override
            public void write(byte[] b) throws IOException {
                write(b, 0, b.length);
            }
        };

        System.setOut(new PrintStream(out, true));
        System.setErr(new PrintStream(out, true));
    }

    public static void updateTextArea(final JTextArea textArea,
            final String text) {
        SwingUtilities.invokeLater(new Runnable() {

            public void run() {
                textArea.append(text);
            }
        });
    }
}

Related Tutorials