LoginSignup
2

More than 5 years have passed since last update.

標準出力をJTextAreaに流す

Last updated at Posted at 2013-02-02

Javaアプレットの開発のとき、printlnの類をコンソールでなく画面内で流してみたいことがあります。
ロガーを使う場合でも、標準出力に出す設定をすれば結局この方法で読むことができます。

標準出力はSystem.setOutを使うとリダイレクト出来ますが、そのためにPrintStreamを作ってやる必要があります。
その際、ByteArrayOutputStreamを使うとバッファ関係を書かずに短くすみます。
受け側はバイト単位なのでマルチバイト文字の切りがいいところでflushが呼ばれるとは限りませんが、autoFlushという引数をtrueにしてやると大体うまくいくようです。

RedirectConsole.java
private static void redirectConsole(JTextArea textarea) {
    ByteArrayOutputStream bytes = new ByteArrayOutputStream() {
        @Override
        public synchronized void flush() throws IOException {
            textarea.setText(toString());
        }
    };

    // trueをつけるといいタイミングでflushされる
    PrintStream out = new PrintStream(bytes, true);

    System.setErr(out);
    System.setOut(out);
}

ログは無制限に溜まっていきますが、ByteArrayOutputStream#resetを呼ぶようにすればクリア出来ます。

RedirectConsole.java
private static void redirectConsole(JTextArea textarea, JButton resetButton) {
    final ByteArrayOutputStream bytes = new ByteArrayOutputStream() {
        @Override
        public synchronized void flush() throws IOException {
            textarea.setText(toString());
        }
    };

    resetButton.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            synchronized (bytes) {
                bytes.reset();
            }
        }
    });

    // trueをつけるといいタイミングでflushされる
    PrintStream out = new PrintStream(bytes, true);

    System.setErr(out);
    System.setOut(out);
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2