19.7 How It All Works
The modularity of the Swing
text components can be confusing.
Fortunately, most of the time it doesn't matter
how it works as long as it
does work. However, some understanding of
what's going on behind the scenes is necessary for
what is to come in the next four chapters.
Let's take a look at what needs to happen for a text
component to be displayed. These behaviors describe the
responsibilities of a JTextArea, but they are
similar for other JTextComponents:
The text component retrieves its UI delegate from the L&F and
installs it. For JTextArea, this might be
javax.swing.plaf.basic.BasicTextAreaUI.
The UI delegate may set properties such as font, foreground, and
selection color. The UI delegate may also set the caret, highlighter,
InputMaps and ActionMap. The
maps allow text components to respond to L&F-specific keyboard
commands for actions such as cut/copy/paste, select-all,
caret-to-end-of-line, page-down, and so on.
The UI delegate also instantiates an EditorKit.
For JTextArea this might be
javax.swing.text.DefaultEditorKit. Most of the
Actions in the text component's
array come from the EditorKit.
If the text component's constructor
didn't receive a Document, it
creates one. JTextArea creates its
Document (a PlainDocument)
directly, but other text components delegate this to the
EditorKit.
The Document is responsible for storing the
component's text content. It does this by breaking
it into a hierarchy of one or more Elements. Each
Element can hold part of the
Document's content and some style
information. JTextArea creates one
Element for each line of text and ignores style
information. Other text components can be more sophisticated.
The text component registers itself as a listener for events it needs
to track. This includes registering as a
DocumentListener so it can update itself in
response to any changes that occur in its
Document.
The text component may delegate or partially delegate
preferredSize, minimumSize, and
maximumSize to the UI delegate.
JTextArea does this, but if its
rows and columns properties are
nonzero, it enforces a minimum on preferredSize.
The UI delegate is responsible for painting the component, but it
uses the EditorKit to paint the text content. The
EditorKit does this by way of a
ViewFactory. The ViewFactory
creates a hierarchy of one or more View objects
from the hierarchy of Element objects. The
View hierarchy is then painted to the screen. A
one-to-one correspondence from Element to
View is typical but not required of the
ViewFactory.
In this chapter, we've shown how easy it is to do
simple things with the Swing text framework. However, if you want to
do more than we've demonstrated in this chapter,
Swing has a lot to offer. In the next four chapters,
we'll examine the rest of the Swing text package,
building many interesting and powerful sample programs as we go.
|