Java Documentation

JTextArea: Multi-line Text Input

JTextArea allows the user to enter multiple lines of text, such as comments or descriptions. Its size is usually specified in rows and columns.

Example: JLabel with a JTextArea

This example uses a label and a multi-line text area with 3 rows and 10 columns, laid out with FlowLayout.

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

class MyFrame extends JFrame {
    MyFrame() {
        setTitle("Components - JTextArea");

        JTextArea ta1 = new JTextArea(3, 10);

        // height 3 - row, width 10 - cols textarea;

        JLabel l1 = new JLabel("Enter your Text:");

        add(l1);
        add(ta1);

        setLayout(new FlowLayout());
        setSize(500, 500);
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

public class JTextAreaDemo {
    public static void main(String[] args) {
        new MyFrame();
    }
}
Reference & full codeView on GitHub

What is JTextArea?

A JTextArea is used when you need a box where the user can enter or view multiple lines of text. It does not have scrollbars by default, but can be wrapped in a JScrollPane.

  • Good for comments, descriptions, or logs.
  • Supports multiple rows and columns (visible area).
  • Text can also be retrieved with getText().

Line-by-line: Understanding the JTextArea example

The JFrame pattern is the same. We focus on the multi-line nature of the text area and the meaning of rows and columns.

JTextArea ta1 = new JTextArea(3, 10);

Creates a text area with 3 rows and 10 columns. Rows control the visible height; columns control the approximate visible width.

JLabel l1 = new JLabel("Enter your Text:");

Label instructs the user about what to type into the text area.

add(l1);
add(ta1);

Adds the label and then the text area to the frame. WithFlowLayout, they appear next to each other or wrap as space runs out.

setLayout(new FlowLayout());

Again uses FlowLayout for a simple arrangement of components.

Where JTextArea is used

You will use JTextArea for larger free-form inputs, such as feedback forms or log viewers. Combined with scroll panes, it becomes a powerful component for showing lots of text.