How to redirect console content to a textArea in Java?

前端 未结 5 575
天涯浪人
天涯浪人 2020-12-05 15:18

I\'m trying to get the content of console in a textArea in java.

For example if we have this code,

class FirstApp {
    public static void main (Stri         


        
相关标签:
5条回答
  • 2020-12-05 15:51

    I found this simple solution:

    First, you have to create a class to replace the standard output:

    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());
        }
    }
    

    Then you replace standards as follows:

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

    The problem is that all the outputs will be showed only in the text area.

    Source with a sample: http://www.codejava.net/java-se/swing/redirect-standard-output-streams-to-jtextarea

    0 讨论(0)
  • 2020-12-05 15:54

    One of the way you can do it by setting the System OutputStream to a PipedOutputStream and connect that to a PipedInputStream that you read from to add text to your component, E.g

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

    Have u looked at the following link ? If not, then you must.

    • Print to textArea instead of console in eclipse ?
    • Redirecting all console o/p to GUI textbox
    • Simple java console - Swing based
    0 讨论(0)
  • 2020-12-05 16:01

    like this http://img122.imageshack.us/img122/5692/dibujoof2.png

    Create Java console inside a GUI panel

    0 讨论(0)
  • 2020-12-05 16:04

    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

    0 讨论(0)
  • 2020-12-05 16:09

    Message Console shows one solution for this.

    0 讨论(0)
提交回复
热议问题