Java Reference
In-Depth Information
insertString(int offset, String text, AttributeSet attrSet)
inserts
the symbols in string
text
before the symbol currently at position
offset
in the document. The new text is formatted as specified in
attrSet
.If
the parameters are outside the current size of the document then a
Bad-
LocationException
will occur.
remove(int offset,int length)
deletes as many symbols as the current value
of
length
, starting with the one currently at position
offset
.Ifthe parameters
are outside the current size of the document then a
BadLocationException
will occur.
The text of a document is often read from some file. This is easily done using the
utility class
EditorKit
, which is also found in the
javax.swing.text
package.
Every Swing component
textComp
that can display documents has an editor kit.
It can be accessed by
textComp.getEditorKit()
.Weneed the following method
from
EditorKit
:
read(FileReader fReader,Document doc,
int
offset);
The file reader should be assigned to the file whose content we want to insert
into the document
doc
. Parameter
offset
specifies that position in the document
before which the file content is inserted. For a new document
offset = 0
is used.
The following code snippet demonstrates the use. We want to read a file
filename
into
DefaultStyledDocument
called
doc
and then display it in a Swing component
textComp
:
DefaultStyledDocument doc =
new
DefaultStyledDocument();
textComp.setDocument(doc);
EditorKit ediKit = textComp.getEditorKit();
FileReader fReader =
new
FileReader(filename);
ediKit.read(fReader,doc,0);
■
18.5
An example of using documents
Program
DocumentFrame
demonstrates the features described in the previous sec-
tions. The text is administered by an instance
styledDoc
of
DefaultStyled-
Document
.Wethen use a
JTextPane
to display the document. The document con-
tent is read from the ASCII file
DocText.txt
.Anumber of attribute sets is defined
in class
DocAtt
. These are then used by
DocumentFrame
to format parts of the
document. Also two position markers are placed in the text.
An anonymous document listener is defined in
DocumentFrame
and assigned to
styledDoc
.Itmonitors the changes made to the document and displays them in
a
DocumentStatusPanel
below the document. Every insertion or deletion of text
results in a line in the status panel describing what happened. The listener also
monitors the two position markers and displays their current positions. We list
only class
DocumentFrame
; the other class is on the topic's home page. Figure 18.5
shows an example.
Search WWH ::
Custom Search