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