11

I currently have a program that prints lines of text to the screen in various manners such as 'System.out.println()' statements and for loops the print all elements in an array to screen.

I am now adding a GUI to this program. My problem is that I want to print everything that prints to eclipse's console to a textbox in my GUI instead. Is this possible and if so how would I go about doing this.

Thanks in Advance.

Nik Reiman
  • 39,067
  • 29
  • 104
  • 160

2 Answers2

22

Check out this blog article, entitled Redirecting System.out and System.err to JTextPane or JTextArea. It describes almost everything you need.

The basic idea is that you create your own specialized output stream. In your implementation of the write() methods, you call some code to append the new data to your text box. Then, you set this new output stream as your System.out by calling System.setOut() or System.setErr().

NOTE: that article is missing one thing. You need to start your program in a separate thread.

Cole Smith
  • 150
  • 1
  • 7
theomega
  • 31,591
  • 21
  • 89
  • 127
  • Thanks for the idea. This site seems to have the things it wants to print to the textarea in the same class as the gui. I want to keep the classes seperate. –  Feb 19 '09 at 11:25
  • He corrected the problem of 2 threads. So the tutorial is correct now. – MJBZA May 11 '16 at 10:21
7

An idea:

Create your own PrintStream that outputs everything to this textbox. Then set this new PrintStream to be the standard output stream like that:

System.setOut(myPrintStream());
Romain Linsolas
  • 79,475
  • 49
  • 202
  • 273