Java Reference
In-Depth Information
Styling text
18
When text is displayed, there is often a need to use different font styles, sizes or
colours to emphasize parts of the text. We now show how this can be done by using
a so-called document model for the text. The model allows style attributes to be
assigned to parts of the text that are automatically moved when text is inserted or
deleted.
Swing provides non-graphical classes that model text documents. They allow ma-
nipulations of the text such as insertion and deletions and the assignment of dif-
ferent styles to different parts of the text. When such a text model is displayed in a
text component, the styles become visible. By using a text model the style and for-
matting are done abstractly and are independent of the display used. Listeners can
be attributed to documents to trigger actions in response to changes in the text.
The
javax.swing.text
sub-library contains the interface
Document
and some
classes implementing this interface. We will use class
DefaultStyledDocument
which supplies many methods to modify the layout of normal (ASCII) text. There
is another predefined class,
HTMLDocument
, which provides a method for styling
HTML formatted text. If these classes do not provide the layout features for the
text under consideration, then one has to define one's own document class by
implementing interface
Document
or by extending an existing class. We proceed
by introducing a number of helper classes for formatting text documents and then
show how they are used.
■
18.1
Positions
Most operations on documents rely on the concept of a
position marker
. These are
defined in class
Position
1
.A
text
is a sequence of letters or symbols. We prefer
the word 'symbols' because spaces and punctuation signs are also considered.
A
position
designates a place between two consecutive symbols. The
offset
of a
position is the number of symbols between it and the beginning of the text. The
position before the first symbol (symbol number zero) has offset 0, the one after
1
The name
Position
is misleading. An instance of
Position
does not specify a position
in the document that is fixed, but one that moves if text is deleted or inserted.
Search WWH ::
Custom Search