JTextArea Example Java Swing

JTextArea Example Java Swing

The limitation of JTextField is that we can enter or display the text in one line only. This limitation is overcome with JTextArea. In JTextArea, we can enter or display any number of lines of text. We can make a text area not to be used by the user by using setEditable(false) method.

Like class JTextField, class JTextArea inherits from JTextComponent, which defines common methods for JTextField, JTextArea and several other text-based GUI components.

In the following JTextArea example, the selected text in the text area is displayed in JOptionPane showMessageDialog box. The text is displayed when the button, display is clicked.


tf = new JTextArea(str,10,30);

The above statement creates a JTextArea object, tf that displays 10 lines and each line containing 30 characters. By default, the string str is displayed in the text area. If extra lines and columns are added, automatically scorllbars will be added.

String s1 = tf.getSelectedText();

The getSelectedText() method returns the selected portion of the text. There is one more method getText() that returns all the text present in the text area.

The color of JTextArea can be changed with setBackground() and setForeground() methods.

The text in the text area can be clear with setText(“”).

Leave a Reply

Your email address will not be published. Required fields are marked *