Redirect System.out & System.err to JTextarea
package test.win;
import java.awt.Dimension;
import java.awt.event.HierarchyBoundsListener;
import java.awt.event.HierarchyEvent;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Date;
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.SpringLayout;
import javax.swing.SwingUtilities;
public class MyFrame extends JFrame implements Runnable {
private JTextArea textArea;
private MyFrame thisFrame;
public MyFrame() {
this.textArea = new JTextArea();
this.thisFrame = this;
this.setOut();
this.getContentPane().setLayout(new SpringLayout());
JScrollPane sPane = new JScrollPane(this.textArea);
sPane.addHierarchyBoundsListener(new HierarchyBoundsListener() {
@Override
public void ancestorMoved(HierarchyEvent e) {
// TODO Auto-generated method stub
}
@Override
public void ancestorResized(HierarchyEvent e) {
// TODO Auto-generated method stub
JScrollPane pane = (JScrollPane) e.getSource();
pane.setPreferredSize(new Dimension(thisFrame.getContentPane().getWidth(), thisFrame.getContentPane().getHeight()));
}
});
this.getContentPane().add(sPane);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(300, 300);
this.setLocation(300, 300);
this.setVisible(true);
}
private void appendText(final String text) {
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
textArea.append(text);
}
});
}
private void setOut() {
OutputStream os = new OutputStream() {
@Override
public void write(int b) throws IOException {
// TODO Auto-generated method stub
appendText(String.valueOf((char) b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
// TODO Auto-generated method stub
appendText(new String(b, off, len));
}
@Override
public void write(byte[] b) throws IOException {
// TODO Auto-generated method stub
write(b, 0, b.length);
}
};
System.setErr(new PrintStream(os, true));
System.setOut(new PrintStream(os, true));
}
@Override
public void run() {
while (true) {
// TODO Auto-generated method stub
try {
Thread.sleep(1000);
System.out.println(new Date());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
new Thread(new MyFrame()).start();
}
}