如何将控制台内容重定向到Java中的textArea?

use*_*111 14 java swing jtextarea

我试图在java中的textArea中获取控制台的内容.

例如,如果我们有这个代码,

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

我想将"Hello World"输出到textArea,我必须选择什么actionPerformed?

cam*_*ckr 6

消息控制台显示了一个解决方案.


Ser*_*age 5

我找到了这个简单的解决方案:

首先,您必须创建一个类来替换标准输出:

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());
    }
}
Run Code Online (Sandbox Code Playgroud)

然后,您按以下方式替换标准:

JTextArea textArea = new JTextArea(50, 10);
PrintStream printStream = new PrintStream(new CustomOutputStream(textArea));
System.setOut(printStream);
System.setErr(printStream);
Run Code Online (Sandbox Code Playgroud)

问题在于所有输出将仅在文本区域中显示。

带有示例的源代码:http : //www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

  • 这几乎是完美的,但是每当控制台输出时,textarea 就会闪烁一堆。而不是附加,使用`textArea.setText(textArea.getText() + String.valueOf((char)paramInt));`代替,它不会像原来的`System.out`那样闪烁和流动。 (2认同)

And*_*s_D 3

您必须重定向System.out到 的自定义、可观察子类PrintStream,以便添加到该流的每个字符或行都可以更新 textArea 的内容(我猜,这是一个 AWT 或 Swing 组件)

PrintStream可以使用 a 创建实例,ByteArrayOutputStream它将收集重定向的输出System.out