如题,要实时重定向到JTextArea。第一步,先实现重定向这一功能,代码如下:
public class JTextAreaOutputStream extends OutputStream { private final JTextArea destination; static private ExecutorService service = Executors.newCachedThreadPool(new ThreadFactory() { @Override public Thread newThread(Runnable r) { return new Thread(r, "output"); } }); public JTextAreaOutputStream (JTextArea destination) { if (destination == null) throw new IllegalArgumentException ("Destination is null"); this.destination = destination; } @Override public void write(byte[] buffer, int offset, int length) throws IOException { final String text = new String (buffer, offset, length); SwingUtilities.invokeLater(new Runnable () { @Override public void run() { destination.append(text); } }); } @Override public void write(int b) throws IOException { write (new byte [] {(byte)b}, 0, 1); }
第二步,在Swing界面对应位置创建上述实体对象,同时实现重定向功能:
JTextAreaOutputStream jto = new JTextAreaOutputStream(jTextArea); System.setOut (new PrintStream(jto));//设置输出重定向 System.setErr(new PrintStream(jto));//将错误输出也重定向,用于e.pritnStackTraced
第三步,在实现重定向功能之后,在相同地方创建一个新的进程执行要执行的有输出的代码:
new Thread(new Runnable() { @Override public void run() { //原本要执行的代码。 } }).start();
如上,问题就已经解决了,如果不加入第三步,则不能实现实时更新JTextArea内容,同时Swing界面会卡死,一直到当前程序执行完毕之后,一次性输出所有内容,此时卡死才会结束。网上查的内容是单线程,当前Swing进程阻塞,用来执行我们要执行的代码,这个时候给其放入另一线程,则不会出现阻塞问题,解决问题。希望有用。