Creating Text Area by Using JTextArea Class

In this tutorial, we will show you how to use JTextArea class to create text area widget.

Unlike the text field, text area allows the user to input multiple lines of text. To create a text area in Swing, you use JTextArea class.

The JTextArea class uses PlainDocument model, therefore, it cannot display multiple fonts. The display area of the JTextArea is controlled by its rows and columns properties. We often use JTextArea with scroll pane to add horizontal and vertical scrollbars.

JTextArea ConstructorsMeaning
public JTextArea ()Creates a new text area. A default model is created. rows/columns are set to 0. The initial text is null.
public  JTextArea(Document doc, String text, int rows, int columns)Creates a new text area with given document and number of columns and rows.
public  JTextArea(String text)Creates a new text area with a given text with row and column are set to 0. A default model is created.
public  JTextArea(int rows, int columns)Creates a new text area with given rows/columns
public  JTextArea(String text, int columns)Creates a new text field with given text and number of columns.

Example of creating a text area by using JTextArea Class

In this example, we create a new text area using the JTextArea class.

Here is the screenshot of the demo application:

JTextArea
package jtextareademo;

import javax.swing.*;
import java.awt.*;

public class Main {

    public static void main(String[] args) {
        final JFrame frame = new JFrame("JTextArea Demo");
        JTextArea ta = new JTextArea(10, 20);

        JScrollPane sp = new JScrollPane(ta);

        frame.setLayout(new FlowLayout());
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(300, 220);
        frame.getContentPane().add(sp);

        frame.setVisible(true);
    }
}Code language: JavaScript (javascript)

In the program above:

  • First, we create a new JTextArea instance ta and init its rows and columns
  • Then, we create a new instance of JScrollPane and pass the JTextArea instance to its constructor.  This adds horizontal and vertical scrollbars.

In this tutorial, you’ve learned how to use JTextArea class to create text area widget. We have also shown you how to use JTextArea class with JScrollPane class to add the horizontal and vertical scrollbar.