import java.io.*; import javax.swing.*; /** Matthew Morgenstern, November 2000 PrintStream subclasses which support println & print to (1) a Textarea of a Swing scrollable JFrame & (2) to a file. */ /** Implements OutputStream methods to a GUI Swing TextArea. */ class GuiOutputStream extends OutputStream { JTextArea jText; public GuiOutputStream(JTextArea jText) { super(); this.jText = jText; } public void close() throws IOException {} public void flush() throws IOException {} public void write(byte[] b, int off, int len) throws IOException { jText.append(new String(b, off, len)); } public void write(byte[] b) throws IOException { write(b, 0, b.length-1);} public void write(int b) throws IOException { jText.append(String.valueOf(b)); } } /** Implements PrintStream to a GUI JFrame scrolling textarea: Primary Usage: new GuiPrintStream(rows, columns, title) */ public class GuiPrintStream extends PrintStream { JTextArea jText; GuiOutputStream gout; JScrollPane scroll; JFrame topFrame; GuiPrintStream(GuiOutputStream gout) { super(gout); //new PrintStream(new GuiOutputStream(jTextArea)) this.gout = gout; this.jText = gout.jText; } /** Creates JFrame w/ scrolling TextArea, rows x columns, & tile: */ public GuiPrintStream(int rows, int columns, String title) { this(new GuiOutputStream(new JTextArea(rows, columns))); scroll = new JScrollPane(jText); topFrame = new JFrame(title); topFrame.getContentPane().add(scroll); topFrame.pack(); topFrame.setVisible(true); // this.topframe is JFrame } /** Usage: PrintStream ps = new GuiPrintStream(); uses defaults */ public GuiPrintStream () {this(25, 35, "Gui Text Output"); } /* Prints Frame's text to PrintStream, eg printFrame(System.out) */ public void printFrame(PrintStream ps) { ps.println(this.jText.getText()); } } /** Implements PrintStream to a File: Usage: new FilePrintStream(filename) */ class FilePrintStream extends PrintStream { FileOutputStream fileout; String filename; private FilePrintStream(FileOutputStream fileout) { super(fileout); // builds PrintStream from OutputStream this.fileout = fileout; } /** Usage: fps = FilePrintStream.create(filename) */ public static FilePrintStream create(String filename) { FileOutputStream fileout = null; try {fileout = new FileOutputStream(filename); }catch (FileNotFoundException e) {e.printStackTrace();} FilePrintStream fps = new FilePrintStream(fileout); fps.fileout = fileout; return fps; } } class myOut { // test driver program public static void main(String[]args) { GuiPrintStream gps = new GuiPrintStream(); FilePrintStream fileps = null; gps.println(gps); gps.println(gps.topFrame); gps.println(gps.gout); gps.println(gps.jText); gps.print("\n*Second test of inner pane\n"); gps.println("Third test println to .ps gui."); gps.printFrame(System.out); fileps = FilePrintStream.create("foo.txt"); gps.printFrame(fileps); } }