Friday, January 17, 2014

Redirect the output to Java Swing textarea

The below example will redirect the System.out to Java Swing text area. If want to redirect java.util.logging.Logger to Java Swing text area. Need override ConsoleHandler to setOutputStream(System.err); to setOutputStream(System.out);

Or update System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
to System.setErr(new PrintStream(new PipedOutputStream(outPipe), true));

package gui;

import java.awt.BorderLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.Scanner;
import java.util.logging.Logger;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;

public class JConsole {

private static Logger logger = Logger.getLogger(JConsole.class.getName());

public static void main(String[] args) throws IOException {
JFrame frame = new JFrame("JConsole");
JTextArea jta = new JTextArea();
JButton button = new JButton("Run");
frame.setLayout(new BorderLayout());
frame.add(button,BorderLayout.NORTH);
frame.add(jta,BorderLayout.CENTER);
button.addActionListener(new ActionListener(){
@Override
public void actionPerformed(ActionEvent e) {
new SwingWorker<Void, Object>(){
@Override
protected Void doInBackground() throws Exception {
outputTest("inner");
return null;
}}.execute();
}});

frame.setSize(400, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
console(jta);
}

public static void outputTest(String msg){
for(int i=0;i<10;i++){
System.out.println(i+" "+msg);
logger.info("Test "+i);
try {
Thread.sleep(500);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}

public static void console(final JTextArea area) throws IOException {
final PipedInputStream outPipe = new PipedInputStream();
System.setOut(new PrintStream(new PipedOutputStream(outPipe), true));
new SwingWorker<Void, String>() {
@Override
protected Void doInBackground() throws Exception {
Scanner s = new Scanner(outPipe);
while (s.hasNextLine()){
String line = s.nextLine();
publish(line + "\n");
}
s.close();
return null;
}

@Override
protected void process(List<String> chunks) {
for (String line : chunks){
area.append(line);
}
}
}.execute();
}

}

No comments:

Post a Comment