Java Reference
In-Depth Information
textArea.setEditable(false);
Now the user can no longer edit the contents of the field, but your program can still
call
setText
and
append
to change it.
As shown in
Figure 4
, the
JTextField
and
JTextArea
classes are subclasses of
the class
JTextComponent
. The methods
setText
and
setEditable
are
defined in the
JTextComponent
class and inherited by
JTextField
and
JTextArea
. However, the
append
method is defined in the
JTextArea
class.
To add scroll bars to a text area, use a
JScrollPane
, like this:
JTextArea textArea = new JTextArea(ROWS, COLUMNS);
JScrollPane scrollPane = new JScrollPane(textArea);
You can add scroll bars to any component with a
JScrollPane
.
Then add the scroll pane to the panel.
Figure 13
shows the result.
The following sample program puts these concepts together. A user can enter
numbers into the interest rate text field and then click on the ȒAdd Interestȓ button).
The interest rate is applied, and the updated balance is appended to the text area. The
text area has scroll bars and is not editable.
483
484
Figure 13
The Investment Application with a Text Area
This program is similar to the previous investment viewer program, but it keeps track
of all the bank balances, not just the last one.