JTextArea Class
Package: javax.swing
The JTextArea
class creates a text area, which is similar to a text field, but it lets the user enter more than one line of text. If the user enters more text in the text area than can be displayed at once, the text area can display a scroll bar to allow the user to see the entire text. Figure 5-12 shows a text area in action.
Figure 5-12
Constructors
Constructor |
Description |
|
Creates a new text area |
|
Creates a new text area large enough to display the specified number of rows and columns |
|
Creates a new text area with the specified initial text value, large enough to display the specified number of rows and columns |
Methods
Method |
Description |
|
Adds the specified text to the end of the text area’s text value. |
|
Gets the number of lines currently in the text value. |
|
Gets the text value entered in the field. |
|
Inserts the specified text at the specified position. |
|
Asks for the focus to be moved to this text field. |
|
Replaces text indicated by the start and end positions with the new specified text. |
|
Sets the width of the text area. (It’s better to do this in the constructor.) |
|
If |
|
If |
|
Sets the field’s text value. |
|
Sets the tooltip text that’s displayed if the user rests the mouse pointer over the text field for a few moments. |
|
If |
Creating a text area
Here’s the code I used to create the text area shown in Figure 5-12:
textNovel = new JTextArea(10, 25);
JScrollPane scroll = new JScrollPane(textNovel,
JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
The first statement creates a text area, giving it an initial size of 10 rows and 25 columns. Then the second statement creates a scroll pane. Notice that the text area object is passed as a parameter to the constructor for the JScrollPane
, along with constants that indicate whether the scroll pane should include vertical or horizontal scroll bars (or both).
Retrieving text from a text area
To retrieve the text that the user enters in a text area, you use the getText
method, like this:
String text = textNovel.getText();
You’ll usually write the code to retrieve text from a text area in the context of an action event listener. For example:
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == buttonOK)
{
String text = textNovel.getText();
if (text.contains(“All work and no play”))
JOptionPane.showMessageDialog(textNovel,
“Can’t you see I’m working?”,
“Going Crazy”,
JOptionPane.ERROR_MESSAGE);
}
}
Here, a message box is displayed if the text contains the string All work and no play
.
Notice that in addition to the getText
method, the JTextArea
class has methods that let you add text to the end of the text area’s current value (append
), insert text into the middle of the value (insert
), and replace text (replace
). You use these methods to edit the value of the text area.
textItinerary = new JTextArea(10, 20);
textItinerary.setLineWrap(true);
textItinerary.setWrapStyleWord(true);