Skip to content

JTextArea Java Swing TextArea Example

Ramesh Fadatare edited this page Jul 9, 2019 · 1 revision

In this post, I show you how to create a text area field using a JTextArea component in Swing-based applications.

A JTextArea is a multiline text area that displays plain text. It is a lightweight component for working with text.

Java Swing TextArea Example

The below example shows a simple JTextArea component:

package net.sourcecodeexamples.swingexample.components2;

import javax.swing.GroupLayout;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Dimension;
import java.awt.EventQueue;

public class TextAreaExample extends JFrame {

    private static final long serialVersionUID = 1 L;

    private void initializeUI() {

        JTextArea area = new JTextArea();
        JScrollPane spane = new JScrollPane(area);

        area.setLineWrap(true);
        area.setWrapStyleWord(true);

        createLayout(spane);

        setTitle("JTextArea");
        setSize(new Dimension(350, 300));
        setDefaultCloseOperation(EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
    }

    private void createLayout(JComponent...arg) {

        JPanel pane = (JPanel) getContentPane();
        GroupLayout gl = new GroupLayout(pane);
        pane.setLayout(gl);

        gl.setAutoCreateContainerGaps(true);
        gl.setAutoCreateGaps(true);

        gl.setHorizontalGroup(gl.createParallelGroup()
            .addComponent(arg[0])

        );

        gl.setVerticalGroup(gl.createSequentialGroup()
            .addComponent(arg[0])
        );

        pack();
    }

    public static void main(String[] args) {
        EventQueue.invokeLater(() - > {
            TextAreaExample textAreaExample = new TextAreaExample();
            textAreaExample.initializeUI();
            textAreaExample.setVisible(true);
        });
    }
}

Let's understand the above program.

We created a JTextArea component as:

JTextArea area = new JTextArea(); 

To make the text scrollable, we put the JTextArea component into the JScrollPane component:

JScrollPane spane = new JScrollPane(area);

The setLineWrap() makes the lines wrapped if they are too long to fit the text area's width:

area.setLineWrap(true);

Here we specify, how is line going to be wrapped. In our case, lines will be wrapped at word boundaries—white spaces:

area.setWrapStyleWord(true);

Output

Clone this wiki locally