Text Components
Swing offers sophisticated text components, from plain-text entry boxes to HTML renderers. For full coverage of Swing’s text capabilities, see O’Reilly’s Java Swing. In that encyclopedic book, several meaty chapters are devoted to text. It’s a huge subject; we’ll just scratch the surface here.
Let’s begin by examining the simpler text components. JTextField is a
single-line text editor and JTextArea is a simple,
multiline text editor. Both JTextField
and JTextArea derive from the
JTextComponent class,
which provides the functionality they have in common. This includes
methods for setting and retrieving the displayed text, specifying whether
the text is “editable” or read-only, manipulating the cursor position
within the text, and manipulating text selections.
Observing changes in text components requires an understanding of
how the components implement the Model-View-Controller (MVC) architecture.
You may recall from the last chapter that Swing components implement a
true MVC architecture. It’s in the text components that you first get an
inkling of a clear separation between the M and VC parts of the MVC
architecture. The model for text components is an object called a Document. When you add or remove text from a
JTextField or a JTextArea, the corresponding Document is changed. It’s the document itself,
not the visual components, that generates text-related events when
something changes. To receive notification of JTextArea changes, therefore, you register with the ...