1   package kerhoswing;
2   
3   import java.io.*;
4   
5   import javax.swing.JTextArea;
6   
7   /**
8    * Simple way to "print" to a JTextArea; just say
9    * PrintWriter out = new PrintWriter(new TextAreaWriter(myTextArea));
10   * Then out.println() et all will all appear in the TextArea.
11   * 
12   * Source: http://javacook.darwinsys.com/new_recipes/14.9betterTextToTextArea.jsp
13   */
14  public final class TextAreaWriter extends Writer {
15  
16      private final JTextArea textArea;
17  
18      /**
19       * @param textArea area where to write
20       * @example
21       * <pre name="test">
22       * #import java.io.*;
23       * #import javax.swing.*;
24       *   JTextArea text = new JTextArea();
25       *   PrintWriter tw = new PrintWriter(new TextAreaWriter(text));
26       *   tw.print("Hello");
27       *   tw.print(" ");
28       *   tw.print("world!");
29       *   text.getText() === "Hello world!";
30       *   text.setText("");
31       *   tw.println("Hello");
32       *   tw.println("world!");
33       *   text.getText() =R= "Hello\\r?\\nworld!\\r?\\n";
34       * </pre>
35       */
36      public TextAreaWriter(final JTextArea textArea) {
37          this.textArea = textArea;
38      }
39  
40      @Override
41      public void flush(){ }
42      
43      @Override
44      public void close(){ }
45  
46      @Override
47      public void write(char[] cbuf, int off, int len) throws IOException {
48          textArea.append(new String(cbuf, off, len));
49      }
50      
51  
52      /**
53       * Factory method for creating a PrintWriter to print to selected TextArea
54       * @param textArea area where to print
55       * @return created PrintWriter ready to print to TextArea
56       * @example
57       * <pre name="test">
58       * #import java.io.*;
59       * #import javax.swing.*;
60       *   JTextArea text = new JTextArea();
61       *   PrintWriter tw = TextAreaWriter.getTextPrintWriter(text);
62       *   tw.print("Hyvää");
63       *   tw.print(" ");
64       *   tw.print("päivää!");
65       *   text.getText() === "Hyvää päivää!";
66       * </pre>
67       */
68      public static PrintWriter getTextPrintWriter(JTextArea textArea) {
69          return new PrintWriter(new TextAreaWriter(textArea)); 
70      }
71  
72  }
73  
74