Two Swing classes support styled text: JEditorPane
and its
subclass JTextPane
. Several
facts about editor panes and text panes were sprinkled throughout the previous
four sections. Here we list the facts again, to collect them in one place and
to provide a bit more detail. The information here should help you understand
the differences between editor panes and text panes, and when to use which.
setPage
method. The JEditorPane
class
also provides constructors that let you initialize an editor pane from a
URL. JTextPane
has no such constructors. See Using
an Editor Pane to Display Text from a URL for an example of using this
feature to load an uneditable editor pane with HTML.
Be aware that the document and editor kit might change when using the
setPage
method. For example, if an editor pane contains plain
text (the default), and you load it with HTML, the document will change to
an HTMLDocument
instance and the editor kit will change to an
HTMLEditorKit
instance. If your program uses the
setPage
method, make sure the code adjusts for possible changes
to the pane's document and editor kit instances (re-register document
listeners on the new document, and so on).
StyledDocument
interface. HTMLDocument
and
RTFDocument
are both StyledDocuments
so HTML and
RTF work as expected within a text pane. If you load a text pane with plain
text though, the text pane's document is not a PlainDocument
as
you might expect, but a DefaultStyledDocument
.
registerEditorKitForContentType
to register your kit with the
JEditorPane
class. By registering an editor kit in this way,
all editor panes and text panes in your program will be able to read, write,
and edit the new format. However, if the new editor kit is not a
StyledEditorKit
, text panes will not support the new format.
StyledDocument
interface. The Swing text package provides a default implementation of this
interface, DefaultStyledDocument
, which is the document text
panes use by default. A text pane also requires that its editor kit be an
instance of a StyledEditorKit
(or a subclass). Be aware that
the read
and write
methods for
StyleEditorKit
write plain text.
JTextPane
class itself contains many methods for working with styles that simply call
methods in its document or editor kit.
JTextPane
class, you can
embed images and components in a text pane. You can embed images in an
editor pane, too, but only by including the images in an HTML or RTF file.