import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import java.awt.Rectangle;
import java.io.OutputStream;
import java.io.IOException;
import java.util.StringTokenizer;

/**
  * This class writes in a Text area like in an OutputStream.
  */
 public class JTextAreaStream extends OutputStream {
		public final static byte [] THE_END_OF_LINE = { 0xd, 0xa };
		public final static String theReturnStr = new String(THE_END_OF_LINE);
		JScrollPane theScroll = null;
		private JTextArea theArea = null;

		public JTextAreaStream( JTextArea anArea, JScrollPane aScrollPane ) {
		  theArea = anArea;
		  theScroll = aScrollPane;
		}
		public void write( int b ) {
		  String out;
		  try {
			 out = Integer.toString( b );
		  }
		  catch( Exception e ) {
			 return;
		  }

		  theArea.append( out );
		}

		public void write( byte[] buf ) throws IOException {
		  write( buf, 0, buf.length );
		}

		public void write( byte[] buf, int off, int len ) {
			String theToAppend = new String( buf, off, len );

			StringTokenizer theStringTok = new StringTokenizer( theToAppend, theReturnStr, true );

			while( theStringTok.hasMoreElements() ) {
				String theNextElement = (String) theStringTok.nextElement();
				theArea.append( theNextElement );
				Rectangle theViewRectangle = theScroll.getViewport().getViewRect();
				Rectangle theAreaRec = theArea.getBounds();

				if ( theViewRectangle.height < theAreaRec.height ){
					theScroll.getViewport().scrollRectToVisible( new Rectangle( theViewRectangle.x, theAreaRec.height - theViewRectangle.height, theViewRectangle.width, theViewRectangle.height ) );
			  	}
			}
		}

		public void clear() {
		  theArea.setText( "" );
		}
 }
