Java Reference
In-Depth Information
JTextArea Class
The
JTextArea
component is the text component for multiple-line input. Similar to the
JTextField
, the data model for a
JTextArea
is the
PlainDocument
implementation of the
Document
interface. Therefore, the
JTextArea
is limited to single-attributed text. As with other
Swing components that may require scrolling, the
JTextArea
doesn't support scrolling itself.
You need to place each
JTextArea
within a
JScrollPane
to allow a user to properly scroll through
the contents of a
JTextArea
.
Creating a JTextArea
There are six constructors for creating a
JTextArea
:
public JTextArea()
JTextArea textArea = new JTextArea();
public JTextArea(Document document)
Document document = new PlainDocument();
JTextArea textArea = new JTextArea(document);
public JTextArea(String text)
JTextArea textArea = new JTextArea("...");
public JTextArea(int rows, int columns)
JTextArea textArea = new JTextArea(10, 40);
public JTextArea(String text, int rows, int columns)
JTextArea textArea = new JTextArea("...", 10, 40);
public JTextArea(Document document, String text, int rows, int columns)
JTextArea textArea = new JTextArea(document, null, 10, 40);
Unless otherwise specified, the text area is able to hold zero rows and columns of content.
Although this might sound like a serious limitation, you're just telling the text area to let the
current
LayoutManager
worry about the size of your text area. The contents of the
JTextArea
are
initially empty unless specified from either the starting text string or the
Document
model.
■
Note
Other initial settings for a
JTextArea
include having a tab stop every eight positions and turning off
word wrap. For more on tab stops, see the
TabStop
and
TabSet
class descriptions in Chapter 16.
After creating a
JTextArea
, remember to place the
JTextArea
into a
JScrollPane
. Then if
there isn't sufficient space on the screen, the
JScrollPane
will manage the scrolling for you.