标准输出重定向到GUI
版权声明:转载时请务必保留以下作者信息和链接
作者:陈维(chenweionline@hotmail.com)作者的网站:http://www.chenwei.mobi
使用控制台运行 Java 程序时,我们只需要在程序中使用System.out.println()等标准输出语句就可以将信息在控制台界面打印出来;而在使用 IDE 运行程序时这些信息会输出在 IDE 的 Output 区域,这也是 IDE 的基本功能之一。实现输出从控制台到GUI并不复杂,只需要将标准输出重定向。
重定向标准输出很easy,System 类里有两个静态方法setErr(PrintStream err) 和 setOut(PrintStream out) 分别用于重定位“标准”错误输出流和“标准”输出流。只需要在程序初始时设置即可:
// GUIPrintStream guiPrintStream = new GUIPrintStream(System.out, jTextArea);
System.setErr(guiPrintStream);
System.setOut(guiPrintStream);
在上面的代码中,我们发现一个新的类 GUIPrintStream,这是我们为 PrintStream 所做的包装。因为我们的输出目标位置是GUI,所以需要在 PrintStream 上做些文章,大家请看下面 GUIPrintStream 的代码:

/**//*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mobi.chenwei.sample.redirectingstandardio;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.SwingUtilities;
import javax.swing.text.JTextComponent;

/** *//**
* 输出到文本组件的流。
*
* @author Chen Wei
* @website www.chenwei.mobi
* @email chenweionline@hotmail.com
*/
public class GUIPrintStream extends PrintStream...{
private JTextComponent component;
private StringBuffer sb = new StringBuffer();

public GUIPrintStream(OutputStream out, JTextComponent component)...{
super(out);
this.component = component;
}

/** *//**
* 重写write()方法,将输出信息填充到GUI组件。
* @param buf
* @param off
* @param len
*/
@Override
public void write(byte[] buf, int off, int len) ...{
final String message = new String(buf, off, len);
SwingUtilities.invokeLater(new Runnable()...{
public void run()...{
sb.append(message);
component.setText(sb.toString());
}
});
}
}
类 GUIPrintStream,继承自 PrintStream 并且对它进行了一些修改。
GUIPrintStream 在构造函数中增加了一个 JTextComponent 变量,它就是我们的目标输出 GUI 组件,它规定了目标输出组件是一个文本组件。接下来覆写了 write(byte[] buf, int off, int len)方法,这个方法原来的作用是将 len 字节从指定的初始偏移量为 off 的 byte 数组写入此流,现在经过我们的修改,变成了将 byte 数组包装成 String 写入目标 GUI 组件。
简单的代码完成了将标准输出重定向到 GUI 的全过程。由此延伸,还可以将标准输出重定向到文本文件、从GUI获取标准输入等,就不一一介绍。
完整样例程序下载:http://download.csdn.net/source/371798
推荐文章 |
