Swing : 将 System.out 重定向到 JTextArea 和 JTextPane
April 30th, 2010
1 comment
最近在用Swing 来编写图形用户界面,其中一个需求就是将System.out.println 的输出重定向到JTextArea组件中,刚开始使用的是《Java 标准输出重定向到GUI 》里的代码,但是在后台需要大量计算的时候,界面出现无响应的情况。后来又经过一番搜索,在 blogspot 找到了一篇文章: 《 Redirecting System.out and System.err to JTextPane or JTextArea》 ( 被墙了),可以实现实时输出的功能,不会出现缓慢的情况。
在 Swing 中,如果想将System.out和System.err 重定向到 JTextPane或者JTextArea,只需要覆盖OutputStream中的write() 方法来将文件附加到 text pane中。
JTextArea 版本:
private void updateTextArea(final String text) {
SwingUtilities.invokeLater(new Runnable() {
public void run() {
textArea.append(text);
}
});
}
private void redirectSystemStreams() {
OutputStream out = new OutputStream() {
@Override
public void write(int b) throws IOException {
updateTextArea(String.valueOf((char) b));
}
@Override
public void write(byte[] b, int off, int len) throws IOException {
updateTextArea(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));
}
评论