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?
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.
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.
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
Message Console shows one solution for this.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With