The first statement stores in area an instance of JTextArea . The three arguments
of the constructor call are the initial value of the text, the number of rows, and
the number of columns. There are other JTextArea constructors; look them up
in the API.
The second statement creates a scroll pane around text area area . The third
statement adds the scroll pane, and with it the text area, to the center of the con-
Figure 17.4 contains, on the left, JFrame jf with a single component as cre-
ated by the code above, as it appears in OS X on the Macintosh. To the right in
Fig 17.4 is the same text area after three more characters have been typed by the
user into the first line of the text area, causing the scroll bars to appear.
A JTextArea has several methods that can be used to manipulate it. Below,
we describe some of them.
Playing with the text
Class JTextArea has the same methods as JTextField for retrieving and
setting the text, making the text area editable or not, retrieving the selected text,
and selecting a portion of the text, so we do not explain them here.
But note this: Even though the text area appears to be two-dimensional, from
the internal view it is simply a String with new-line characters '\n' in it. Thus,
your program will probably have to do more to process the retrieved text than it
would to process the text of a text field.
Playing with the number of rows and columns
Getter methods getColumns() and getRows() and corresponding setter
methods exist. So it is possible to change the size of the text area while the pro-
gram is running. If the size is changed, the JFrame should be packed again.
The default in a text area is not to wrap text. So, when the user types in a
text area, the scroll bar adjusts to show the portion that contains the cursor where
characters are being typed. However, you can set the text area to wrap the text
using the method call:
area.setLineWrap( true );
Now, when the cursor goes past the right end of the text area, automatically
the next characters are placed on the next line. When wrapping, the default is to
wrap at character boundaries. Execute the following method call to wrap at word
area.setWrapStyleWord( true );