Forum Stats

  • 3,728,690 Users
  • 2,245,675 Discussions
  • 7,853,705 Comments

Discussions

System.out.println() Print to JFrame

843806
843806 Member Posts: 49,998
edited November 2007 in Swing
I just wrote a rather large java application and now want to develop a GUI for it. I have never developed GUI and am trying to use the API's for help. Can anyone point me in the right direction: I am trying to take everything that is printed out with System.out.println() and print it inside a JFrame. Any help would be magnificent.

-Alex

Comments

  • 843806
    843806 Member Posts: 49,998
    Add a JTextArea to your frame, create a TextAreaOutputStream with it, and use System.setOut(...) to set System.ouot
    /*
     * Created on Mar 13, 2005 by @author Tom Jacobs
     *
     */
    package tjacobs;
    
    import java.io.IOException;
    import java.io.OutputStream;
    
    import javax.swing.JTextArea;
    import javax.swing.text.JTextComponent;
    
    /**
     * TextAreaOutputStream creates an outputstream that will output to the
     * given textarea. Useful in setting System.out
     */
    public class TextAreaOutputStream extends OutputStream {
    	public static final int DEFAULT_BUFFER_SIZE = 1;
    	
    	JTextArea mText;
    	byte mBuf[];
    	int mLocation;
    	public TextAreaOutputStream(JTextArea component) {
    		this(component, DEFAULT_BUFFER_SIZE);
    	}
    
    	public TextAreaOutputStream(JTextArea component, int bufferSize) {
    		mText = component;
    		if (bufferSize < 1) bufferSize = 1;
    		mBuf = new byte[bufferSize];
    		mLocation = 0;
    	}
    	@Override
    	public void write(int arg0) throws IOException {
    		//System.err.println("arg = "  + (char) arg0);
    		mBuf[mLocation++] = (byte)arg0;
    		if (mLocation == mBuf.length) {
    			flush();
    		}
    	}
    	
    	public void flush() {
    		mText.append(new String(mBuf, 0, mLocation));
    		mLocation = 0;
    /*
    		try {
    			Thread.sleep(1);
    		}
    		catch (Exception ex) {}
    	}
    	*/
    	}
    }
  • 843806
    843806 Member Posts: 49,998
    Thanks for the sample, it's very useful :)
This discussion has been closed.