All Classes Namespaces Files Functions Variables
TextAreaOutputStream.java
Go to the documentation of this file.
1 package fi.jyu.mit.fxgui;
2 
3 import java.io.IOException;
4 import java.io.OutputStream;
5 import java.io.PrintStream;
6 
7 import javafx.scene.control.TextArea;
8 
9 
10 /**
11  * Simple way to "print" to a JTextArea; just say
12  * PrintStream out = new PrintStream(new TextAreaOutputStream(myTextArea));
13  * Then out.println() et all will all appear in the TextArea.
14  * Source: http://javacook.darwinsys.com/new_recipes/14.9betterTextToTextArea.jsp
15  */
16 public final class TextAreaOutputStream extends OutputStream {
17 
18  private final TextArea textArea;
19  // private final StringBuilder sb = new StringBuilder();
20 
21  /**
22  * @param textArea area where to write
23  * @example
24  * <pre name="test">
25  * #import java.io.*;
26  * #import javax.swing.*;
27  * JTextArea text = new JTextArea();
28  * PrintStream tw = new PrintStream(new TextAreaOutputStream(text));
29  * tw.print("Hello");
30  * tw.print(" ");
31  * tw.print("world!");
32  * tw.flush();
33  * text.getText() === "Hello world!";
34  * text.setText("");
35  * tw.println("Hello");
36  * tw.println("world!");
37  * text.getText() =R= "Hello\\r?\\nworld!\\r?\\n";
38  * </pre>
39  */
40  public TextAreaOutputStream(final TextArea textArea) {
41  this.textArea = textArea;
42  }
43 
44  @Override
45  public void flush(){
46  //textArea.append(sb.toString());
47  //sb.setLength(0);
48  }
49 
50  @Override
51  public void close(){ /* */ }
52 
53  @Override
54  public void write(int b) throws IOException {
55  /*
56  if (b == '\r')
57  return;
58 
59  if (b == '\n') {
60  textArea.append(sb.toString()+"\n");
61  sb.setLength(0);
62  return;
63  }
64 
65  sb.append((char)b);
66  */
67  //textArea.append(Character.toString((char)b));
68  write(new byte[] {(byte) b}, 0, 1);
69  }
70 
71  @Override
72  public void write(byte b[], int off, int len) throws IOException {
73  textArea.appendText(new String(b, off, len));
74  }
75 
76 
77  /**
78  * Factory method for creating a PrintStream to print to selected TextArea
79  * @param textArea area where to print
80  * @return created PrintStream ready to print to TextArea
81  * @example
82  * <pre name="test">
83  * #import java.io.*;
84  * #import javax.swing.*;
85  * JTextArea text = new JTextArea();
86  * PrintStream tw = TextAreaOutputStream.getTextPrintStream(text);
87  * tw.print("Hyvää"); // skandit toimi
88  * tw.print(" ");
89  * tw.print("päivää!");
90  * text.getText() === "Hyvää päivää!";
91  * text.setText("");
92  * tw.print("ä");
93  * text.getText() === "ä";
94  * </pre>
95  */
96  public static PrintStream getTextPrintStream(TextArea textArea) {
97  return new PrintStream(new TextAreaOutputStream(textArea)); //,true,"ISO-8859-1");
98  }
99 
100 }
101