Http://tech.it168.com/jd/2007-08-28/200708272134409.shtml
[It168 technical documentation]
Recently, when I made an interface for the server of a project, I had to worry about it in order to redirect the information that was originally printed in the background to the GUI. In the past, most of the information was printed and tested using system. Out and system. Err. The diagram is convenient and does not use the log function. Of course this is a bad habit.
At the beginning, swing was used as a panel and the jtextpane component was used as a container for printing information. It may be that swing is not used for too long. During the test, the horizontal sliding block of this item always automatically slides to the last place as the information is displayed, and the printed information looks messy. Later, SWT was used to replace the printed information container with the text component, and the style was defined as SWT. Mult | SWT. v_scroll | SWT. Wrap, so that it can automatically wrap.
Check the jdk api documentation. The system class provides the redirection Methods setout (printstream out), seterr (printstream ERR), and setin (inputstream in ). Here, we only need to use setout and seterr. Both methods need to input a printstream type parameter, you only need to call these two methods before calling the print information to reset the output stream and error stream. We inherit the printstream class and pass the component for displaying information to this custom print stream class as a parameter.
Public class myprintstream extends printstream {private text; Public myprintstream (outputstream out, text) {super (out); this. TEXT = text;}/***** // ***** here, all printing methods must be called */Public void write (byte [] Buf, int off, int Len) {final string message = new string (BUF, off, Len);/** // * SWT non-interface thread access method */display. getdefault (). syncexec (New thread () {public void run () {/** // * add the information to the component */text. append (Message );}});}}
Pass the component as a parameter to the print stream, rewrite the write (byte [] Buf, int off, int Len) method of the parent class, and add the written information to the component, note that the constructor with outputstream is overloaded.
Note that the component has been correctly created before the call printing information is added. In addition, you must register different GUI components to access the thread, like the above SWT, there are strict rules on interface access.
After printstream is completed, the following method is used:
MyPrintStream mps = new MyPrintStream(System.out, text);System.setOut(mps);System.setErr(mps);
In this way, all system. Out and system. Err information in the original program can be transferred to your GUI.