【问题标题】:How to redirect console content to a textArea in Java?如何将控制台内容重定向到 Java 中的 textArea?
【发布时间】:2011-07-03 17:15:16
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java swing jtextarea


    【解决方案1】:

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

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

    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

    【讨论】:

    • 这几乎是完美的,但是每当控制台输出时,textarea 就会闪现一堆。而不是追加,而是使用textArea.setText(textArea.getText() + String.valueOf((char)paramInt));,它不会像原来的System.out那样闪烁和流动。
    • 您可能必须使用 SwingUtilities.invokeLater() 才能工作。
    【解决方案2】:

    Message Console 显示了一种解决方案。

    【讨论】:

      【解决方案3】:
      【解决方案4】:

      您可以通过将System OutputStream 设置为PipedOutputStream 并将其连接到您从中读取的PipedInputStream 来将文本添加到您的组件,例如

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

      你看过下面的链接吗?如果没有,那么你必须。

      【讨论】:

        【解决方案5】:

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2016-07-01
          • 1970-01-01
          • 2016-02-03
          • 1970-01-01
          • 2016-10-21
          • 1970-01-01
          • 2012-02-01
          相关资源
          最近更新 更多