Java Reference
In-Depth Information
Discussion
This is such a common need that I've added it to the DarwinSys package (see Downloading
and Using the Code Examples ). Here is the code for com.darwinsys.io.TextAreaWriter :
package
package com . darwinsys . io ;
import
import java.io.IOException
java.io.IOException ;
import
import java.io.Writer
java.io.Writer ;
import
import javax.swing.JTextArea
javax.swing.JTextArea ;
/**
* Simple way to "print" to a JTextArea; just say
* PrintWriter out = new PrintWriter(new TextAreaWriter(myTextArea));
* Then out.println() et all will all appear in the TextArea.
*/
public
public final
final class
class TextAreaWriter
TextAreaWriter extends
extends Writer {
private
private final
final JTextArea textArea ;
public
public TextAreaWriter ( final
final JTextArea textArea ) {
this
this . textArea = textArea ;
}
@Override
public
public void
void flush (){ }
@Override
public
public void
void close (){ }
@Override
public
public void
void write ( char
char [] cbuf , int
int off , int
int len ) throws
throws IOException {
textArea . append ( new
new String ( cbuf , off , len ));
}
}
As you can see, for the Writer case I only had to override one write() form; all the other
forms of write() , and the print() / println() methods in PrintWriter , call down through
this one method. The flush() and close() methods are also abstract in Writer , but they
don't have to do anything here (though close() could set the textArea field to null , and
write() could check that, to guard against use of a closed Writer ).
Search WWH ::




Custom Search