Java Reference
In-Depth Information
CHAPTER 16
■ ■ ■
Advanced Text Capabilities
I
n Chapter 15, you were introduced to the myriad capabilities of the Swing text components.
In this chapter, you'll continue on the same path by looking at some advanced capabilities that
will prove useful in special situations.
The Swing text components ship with many prefabricated features. For instance, as you
saw in Chapter 15, although text components have methods such as
cut()
,
copy()
, and
paste()
to work with the system clipboard, you really don't need to use them. This is because the Swing
text components come with their own predefined set of
Action
objects, which you'll explore in
this chapter. To use
Action
objects, just attach them to a component, such as a button or menu
item, and then simply select the component that triggers the
Action
. For text components, the
Action
object is an instance of
TextAction
, which has a nice additional feature of knowing
which text component last had the input focus.
In this chapter, you'll also look at how to create stylized text for display in a
JTextPane
.
If you want to display multicolored text documents or different font styles, the
JTextPane
component provides a series of interfaces and classes to describe the attributes attached to
the document. The
AttributeSet
interface gives you these on a read-only basis, and the
MutableAttributeSet
interface extends
AttributeSet
in order to set attributes. You'll see how
the
SimpleAttributeSet
class implements both of these interfaces by offering a
Hashtable
to
store the text attributes, and how the
StyleConstants
class helps to configure the many text
attributes you can apply. And, you'll learn how to work with tab stops within your text documents,
including how to define leader characters and how text is aligned.
Next, you'll get a glimpse of the different editor kits that Swing provides, focusing on the
inner workings of the
HTMLDocument
. When the
JEditorPane
displays HTML, the
HTMLEditorKit
controls how to load and display the HTML content into an
HTMLDocument
. You'll see how the
parser loads the content and how to iterate through the different tags in the document.
Lastly, you'll learn how to take advantage of the formatted input options and validation
available with the
JFormattedTextField
component. You'll see how to provide for formatted
dates and numbers, as well as masked input like telephone and social security numbers.
Using Actions with Text Components
The
TextAction
class is a special case of the
Action
interface that was defined with the other
Swing event-handling capabilities in Chapter 2 and briefly reviewed in Chapter 15. The purpose
of the
TextAction
class is to provide concrete
Action
implementations that can work with text
components. These implementations are smart enough to know which text component most
recently had the input focus and therefore should be the subject of the action.
585