Home > Java > Swing : 将 System.out 重定向到 JTextArea 和 JTextPane

Swing : 将 System.out 重定向到 JTextArea 和 JTextPane

最近在用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));
  }

JTextPanel  版本:

  private void updateTextPane(final String text) {
    SwingUtilities.invokeLater(new Runnable() {
      public void run() {
        Document doc = textPane.getDocument();
        try {
          doc.insertString(doc.getLength(), text, null);
        } catch (BadLocationException e) {
          throw new RuntimeException(e);
        }
        textPane.setCaretPosition(doc.getLength() - 1);
      }
    });
  }

  private void redirectSystemStreams() {
    OutputStream out = new OutputStream() {
      @Override
      public void write(final int b) throws IOException {
        updateTextPane(String.valueOf((char) b));
      }

      @Override
      public void write(byte[] b, int off, int len) throws IOException {
        updateTextPane(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));
  }

在Swing编程中,需要很注意多线程的使用,不然很容易导致界面响应缓慢甚至假死状态,接下来需要学习的是 SwingWorker这个类。

Related posts:

  1. Swing : 将 System.out 重定向到 JTextArea 和 JTextPane (2)
  2. Java IO 简介
  3. Java 的构造方法
  4. 对称矩阵
  5. 蛇形矩阵
Categories: Java Tags: ,
  1. May 5th, 2010 at 01:10 | #1

    wanna to try it!

    ReplyReply
  1. No trackbacks yet.