The TextArea component in swing is similar to the TextArea component in AWT as it allows to display and edit multiple lines of plaintext. But unlike TextArea component in AWT, if all the text cannot be displayed in the available space in the component, scrollbars are not automatically added. In order to add scrollbars, you must insert it into a ScrollPane.
Commonly used methods of this latter component are:
Methods | Description |
public JTextArea (): | creates a new text area with 0 rows and columns; |
public JTextArea (int rows, int columns) | created with the number of rows and columns; |
public JTextArea (String text, int rows, int columns): | same as above but with an initial text; |
getRows public int (): | returns the number of rows; |
getColumns public int (): | Returns the number of columns; |
public void append (String text): | concatenates the text at the end of the existing text in the JTextArea; |
public void insert (String text, int position | Inserts text at the specified position |
This component is often used within a JScrollPane container. Thus when the number of lines is that the component is larger than the space allocated for distribution manager scroll bars appear.
import javax.swing.*;
import java.awt.*;
class JTextAreaExample extends JFrame
{
JTextAreaExample()
{
setLayout(new FlowLayout());
JLabel label = new JLabel("Comments : ");
JTextArea txtArea = new JTextArea("TextArea with 3 rows and 15 column",3,15);
txtArea.setLineWrap(true);
txtArea.setWrapStyleWord(true);
add(label);
add(txtArea);
}
}
class JTextAreaJavaExample
{
public static void main(String args[])
{
JTextAreaExample frame = new JTextAreaExample();
frame.setTitle("JTextArea in Java Swing Example");
frame.setBounds(200,250,350,150);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
}
}