001package fi.jyu.mit.fxgui; 002 003import java.io.*; 004 005import javafx.scene.control.TextArea; 006 007 008/** 009 * Simple way to "print" to a JTextArea; just say 010 * PrintWriter out = new PrintWriter(new TextAreaWriter(myTextArea)); 011 * Then out.println() et all will all appear in the TextArea. 012 * 013 * Source: http://javacook.darwinsys.com/new_recipes/14.9betterTextToTextArea.jsp 014 */ 015public final class TextAreaWriter extends Writer { 016 017 private final TextArea textArea; 018 019 /** 020 * @param textArea area where to write 021 * @example 022 * <pre name="test"> 023 * #import java.io.*; 024 * #import javax.swing.*; 025 * JTextArea text = new JTextArea(); 026 * PrintWriter tw = new PrintWriter(new TextAreaWriter(text)); 027 * tw.print("Hello"); 028 * tw.print(" "); 029 * tw.print("world!"); 030 * text.getText() === "Hello world!"; 031 * text.setText(""); 032 * tw.println("Hello"); 033 * tw.println("world!"); 034 * text.getText() =R= "Hello\\r?\\nworld!\\r?\\n"; 035 * </pre> 036 */ 037 public TextAreaWriter(final TextArea textArea) { 038 this.textArea = textArea; 039 } 040 041 @Override 042 public void flush(){ /* */ } 043 044 @Override 045 public void close(){ /* */ } 046 047 @Override 048 public void write(char[] cbuf, int off, int len) throws IOException { 049 textArea.appendText(new String(cbuf, off, len)); 050 } 051 052 053 /** 054 * Factory method for creating a PrintWriter to print to selected TextArea 055 * @param textArea area where to print 056 * @return created PrintWriter ready to print to TextArea 057 * @example 058 * <pre name="test"> 059 * #import java.io.*; 060 * #import javax.swing.*; 061 * JTextArea text = new JTextArea(); 062 * PrintWriter tw = TextAreaWriter.getTextPrintWriter(text); 063 * tw.print("Hyvää"); 064 * tw.print(" "); 065 * tw.print("päivää!"); 066 * text.getText() === "Hyvää päivää!"; 067 * </pre> 068 */ 069 public static PrintWriter getTextPrintWriter(TextArea textArea) { 070 return new PrintWriter(new TextAreaWriter(textArea)); 071 } 072 073} 074