Swing : 将 System.out 重定向到 JTextArea 和 JTextPane (2)
以前写过一篇文章,《Swing : 将 System.out 重定向到 JTextArea 和 JTextPane》,只提及了如何通过重写来进行流的重定向,没有提供一个良好的接口来直接使用,今天看到:
所以利用睡前的一点时间,重新封装了一下之前的代码,原理不变,代码如下:
package org.leeing.swing.util;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JTextArea;
import javax.swing.SwingUtilities;
/**
* 工具类,将 stdout 及 stderr 重定向到 JTextArea
* @author leeing
*/
public class PrintUtil {
private static void updateTextArea(final JTextArea textArea,final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
public static void redirectSystemStreams(final JTextArea textArea) {
OutputStream out = new OutputStream() {
@Override
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));
}
}
在使用的时候,只要简单地使用下面的一句代码即可实现重定向:
PrintUtil.redirectSystemStreams(OutputTextArea);
其中,OutputTextArea 是某个 JTextArea 的实例,此时用 System.out.println 或 System.err.println 都会打印到 OutputTextArea中去。
至于JTextPane的写法,参照上边的代码,稍作封装就可以了。: )
Related posts:
评论