16

我正在尝试在 java 的 textArea 中获取控制台的内容。

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

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

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

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

消息控制台为此提供了一种解决方案。

于 2011-02-24T17:27:06.953 回答
3

您可以通过将 a 设置System OutputStream为 aPipedOutputStream并将其连接到PipedInputStream您从中读取的 a 以将文本添加到您的组件来做到这一点的一种方法,例如

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 回答
3

You'll have to redirect System.out to a custom, observable subclass of PrintStream, so that each char or line added to that stream can update the content of the textArea (I guess, this is an AWT or Swing component)

The PrintStream instance could be created with a ByteArrayOutputStream, which would collect the output of the redirected System.out

于 2011-02-24T16:48:22.377 回答