16

javaのtextAreaでコンソールのコンテンツを取得しようとしています。

たとえば、このコードがある場合、

class FirstApp {
    public static void main (String[] args){
        System.out.println("Hello World");
    }
}

「Hello World」をテキストエリアに出力したいのですが、どのアクションを実行すればよいですか?

4

5 に答える 5

9

この簡単な解決策を見つけました:

まず、標準出力を置き換えるクラスを作成する必要があります。

public class CustomOutputStream extends OutputStream {
    private JTextArea textArea;

    public CustomOutputStream(JTextArea textArea) {
        this.textArea = textArea;
    }

    @Override
    public void write(int b) throws IOException {
        // redirects data to the text area
        textArea.append(String.valueOf((char)b));
        // scrolls the text area to the end of data
        textArea.setCaretPosition(textArea.getDocument().getLength());
        // keeps the textArea up to date
        textArea.update(textArea.getGraphics());
    }
}

次に、標準を次のように置き換えます。

JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);

問題は、すべての出力がテキスト領域にのみ表示されることです。

サンプル付きのソース: http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

于 2016-07-29T17:54:49.157 に答える
8

メッセージコンソールは、このための1つの解決策を示しています。

于 2011-02-24T17:27:06.953 に答える
3

System.outそのストリームに追加された各文字または行が textArea のコンテンツを更新できるように、のカスタムの監視可能なサブクラスにリダイレクトする必要がありますPrintStream(これは AWT または Swing コンポーネントであると思います)。

インスタンスは、リダイレクトされたの出力を収集する でPrintStream作成できますByteArrayOutputStreamSystem.out

于 2011-02-24T16:48:22.377 に答える
3

System OutputStreamを aに設定PipedOutputStreamし、それを読み取り元の に接続してPipedInputStream、コンポーネントにテキストを追加する方法の 1 つです。

PipedOutputStream pOut = new PipedOutputStream();   
System.setOut(new PrintStream(pOut));   
PipedInputStream pIn = new PipedInputStream(pOut);  
BufferedReader reader = new BufferedReader(new InputStreamReader(pIn));

次のリンクを見ましたか?そうでない場合は、する必要があります。

于 2011-02-24T16:57:46.180 に答える