版权声明:转载时请务必保留以下作者信息和链接
作者:陈维(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);
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.
* To change this template, choose Tools | Templates
* and open the template in the editor.