Java Reference
In-Depth Information
The
rows
and
columns
properties come directly from the constructor arguments. The
preferredScrollableViewportSize
and
scrollableTracksViewportWidth
properties come from
implementing the
Scrollable
interface for scrolling support. The
font
and
preferredSize
properties merely customize the behavior inherited from
JTextComponent
.
That leaves the more interesting properties of
lineCount
,
tabSize
, and
lineWrap
with
wrapStyleWord
to examine. The
lineCount
property allows you to find out how many lines are
in the text area. This is useful for sizing purposes. The
tabSize
property allows you to control
the tab position interval within the text area. By default, this value is 8.
The
lineWrap
and
wrapStyleWord
properties work together. By default, the wrapping of
long lines is disabled. If you enable line wrapping (by setting the
lineWrap
property to
true
), the
point at which long lines wrap depends on the
wrapStyleWord
property setting. Initially, this
property is
false
, which means that if the
lineWrap
property is
true
, line wrapping happens at
character boundaries. If both
lineWrap
and
wrapStyleWord
are
true
, then each word from a line
that doesn't fit is wrapped to another line, as it is in a word processor. So, to get the word wrap
capabilities that most people want, you should set both properties to
true
for your
JTextArea
:
JTextArea textArea = new JTextArea("...");
textArea.setLineWrap(true);
textArea.setWrapStyleWord(true);
JScrollPane scrollPane = new JScrollPane(textArea);
■
Note
The Ctrl-Tab and Shift-Ctrl-Tab key combinations allow users to change focus from within
JTextArea
components without needing to subclass the component.
Handling JTextArea Events
No events are specific to a
JTextArea
. You can use one of the inherited listeners from
JTextComponent
(or one of its parents) or attach an
InputVerifier
.
At times, you'll just have a
JTextArea
on the screen and get its contents after the user
presses a button. Other times, there's a bit more planning involved, where you might monitor
input as it is entered, and possibly convert something like
:-)
to a smiley face:
☺
.
Customizing a JTextArea Look and Feel
Each installable Swing look and feel provides a different
JTextArea
appearance and set of
default
UIResource
values. Figure 15-18 shows the appearance of the
JTextArea
component for
the preinstalled set of look and feel types. Notice that the primary difference in the appearance
of each is the scrollbar from the
JScrollPane
, which is not a part of the actual
JTextArea
.