001package fi.jyu.mit.fxgui; 002 003import java.io.IOException; 004import java.io.OutputStream; 005import java.io.PrintStream; 006 007import javafx.scene.control.TextArea; 008 009 010/** 011 * Simple way to "print" to a JTextArea; just say 012 * PrintStream out = new PrintStream(new TextAreaOutputStream(myTextArea)); 013 * Then out.println() et all will all appear in the TextArea. 014 * Source: http://javacook.darwinsys.com/new_recipes/14.9betterTextToTextArea.jsp 015 */ 016public final class TextAreaOutputStream extends OutputStream { 017 018 private final TextArea textArea; 019 // private final StringBuilder sb = new StringBuilder(); 020 021 /** 022 * @param textArea area where to write 023 * @example 024 * <pre name="test"> 025 * #import java.io.*; 026 * #import javax.swing.*; 027 * JTextArea text = new JTextArea(); 028 * PrintStream tw = new PrintStream(new TextAreaOutputStream(text)); 029 * tw.print("Hello"); 030 * tw.print(" "); 031 * tw.print("world!"); 032 * tw.flush(); 033 * text.getText() === "Hello world!"; 034 * text.setText(""); 035 * tw.println("Hello"); 036 * tw.println("world!"); 037 * text.getText() =R= "Hello\\r?\\nworld!\\r?\\n"; 038 * </pre> 039 */ 040 public TextAreaOutputStream(final TextArea textArea) { 041 this.textArea = textArea; 042 } 043 044 @Override 045 public void flush(){ 046 //textArea.append(sb.toString()); 047 //sb.setLength(0); 048 } 049 050 @Override 051 public void close(){ /* */ } 052 053 @Override 054 public void write(int b) throws IOException { 055 /* 056 if (b == '\r') 057 return; 058 059 if (b == '\n') { 060 textArea.append(sb.toString()+"\n"); 061 sb.setLength(0); 062 return; 063 } 064 065 sb.append((char)b); 066 */ 067 //textArea.append(Character.toString((char)b)); 068 write(new byte[] {(byte) b}, 0, 1); 069 } 070 071 @Override 072 public void write(byte b[], int off, int len) throws IOException { 073 textArea.appendText(new String(b, off, len)); 074 } 075 076 077 /** 078 * Factory method for creating a PrintStream to print to selected TextArea 079 * @param textArea area where to print 080 * @return created PrintStream ready to print to TextArea 081 * @example 082 * <pre name="test"> 083 * #import java.io.*; 084 * #import javax.swing.*; 085 * JTextArea text = new JTextArea(); 086 * PrintStream tw = TextAreaOutputStream.getTextPrintStream(text); 087 * tw.print("Hyvää"); // skandit toimi 088 * tw.print(" "); 089 * tw.print("päivää!"); 090 * text.getText() === "Hyvää päivää!"; 091 * text.setText(""); 092 * tw.print("ä"); 093 * text.getText() === "ä"; 094 * </pre> 095 */ 096 public static PrintStream getTextPrintStream(TextArea textArea) { 097 return new PrintStream(new TextAreaOutputStream(textArea)); //,true,"ISO-8859-1"); 098 } 099 100} 101