You can also append s to the text field or insert s at index i. The second
statement below changes text field field to field[0..i-1] + s + field[i..] .
Playing with the selection
The user may select, or highlight, part the text in the text area. Your program
can retrieve the selected text using the first statement shown below. Your pro-
gram can also change the highlight. The second statement below selects or high-
lights all the text, while the third statement selects only field[i..j-1] .
String selected= field.getSelectedText();
Playing with the number of columns
Getter method getColumns() and a corresponding setter method exist, so it
is possible to change the size of the text field while the program is running. If the
size is changed, the JFrame should be packed again.
Putting text areas into a JFrame
An instance of class JTextArea is a two-dimensional field of editable text,
called simply a text area . A JTextArea is shown in Fig. 17.2. That text area has
a significant problem in that if too much text is placed in it —either long lines or
too many lines— it will be difficult for the user to use. It would be better if the
text area had scroll bars on it.
Below, we show code to create a text area with scroll bars and place it in the
center of JFrame jf —the scroll bars appear only if needed.
Get a class that
from a footnote.
JTextArea area= new JTextArea("012345678\nabc", 5, 11);
JScrollPane scrollPane= new JScrollPane(area);
Two snapshots of a JFrame with a JTextArea