package kerhoswing; import java.io.IOException; import java.io.OutputStream; import java.io.PrintStream; import javax.swing.JTextArea; /** * Simple way to "print" to a JTextArea; just say * PrintStream out = new PrintStream(new TextAreaOutputStream(myTextArea)); * Then out.println() et all will all appear in the TextArea. * Source: http://javacook.darwinsys.com/new_recipes/14.9betterTextToTextArea.jsp */ public final class TextAreaOutputStream extends OutputStream { private final JTextArea textArea; // private final StringBuilder sb = new StringBuilder(); /** * @param textArea area where to write * @example *
     * #import java.io.*;
     * #import javax.swing.*;
     *   JTextArea text = new JTextArea();
     *   PrintStream tw = new PrintStream(new TextAreaOutputStream(text));
     *   tw.print("Hello");
     *   tw.print(" ");
     *   tw.print("world!");
     *   tw.flush();
     *   text.getText() === "Hello world!";
     *   text.setText("");
     *   tw.println("Hello");
     *   tw.println("world!");
     *   text.getText() =R= "Hello\\r?\\nworld!\\r?\\n";
     * 
*/ public TextAreaOutputStream(final JTextArea textArea) { this.textArea = textArea; } @Override public void write(int b) throws IOException { /* if (b == '\r') return; if (b == '\n') { textArea.append(sb.toString()+"\n"); sb.setLength(0); return; } sb.append((char)b); */ //textArea.append(Character.toString((char)b)); write(new byte[] {(byte) b}, 0, 1); } @Override public void write(byte b[], int off, int len) throws IOException { textArea.append(new String(b, off, len)); } /** * Factory method for creating a PrintStream to print to selected TextArea * @param textArea area where to print * @return created PrintStream ready to print to TextArea * @example *
     * #import java.io.*;
     * #import javax.swing.*;
     *   JTextArea text = new JTextArea();
     *   PrintStream tw = TextAreaOutputStream.getTextPrintStream(text);
     *   tw.print("Hyvää"); // skandit toimi
     *   tw.print(" ");
     *   tw.print("päivää!");
     *   text.getText() === "Hyvää päivää!";
     *   text.setText("");
     *   tw.print("ä");
     *   text.getText() === "ä"; 
     * 
*/ public static PrintStream getTextPrintStream(JTextArea textArea) { return new PrintStream(new TextAreaOutputStream(textArea)); //,true,"ISO-8859-1"); } }