Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to redirect console content to a textArea in Java?

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 (String[] args){
        System.out.println("Hello World");
    }
}

and I want to output the "Hello World" to a textArea, what actionPerformed do I have to choose?

like image 703
user618111 Avatar asked Feb 24 '11 16:02

user618111


People also ask

What is JTextArea in Java?

A JTextArea is a multi-line area that displays plain text. It is intended to be a lightweight component that provides source compatibility with the java. awt. TextArea class where it can reasonably do so.

What is the difference between TextArea and TextField in Java?

The main difference between TextField and TextArea in Java is that the TextField is an AWT component that allows entering a single line of text in a GUI application while the TextArea is an AWT component that allows entering multiple lines of text in a GUI application.


3 Answers

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

like image 132
Sertage Avatar answered Oct 09 '22 23:10

Sertage


Message Console shows one solution for this.

like image 22
camickr Avatar answered Oct 09 '22 22:10

camickr


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

like image 27
Andreas Dolk Avatar answered Oct 09 '22 22:10

Andreas Dolk