How do I wrap the text lines in JTextArea?

To wrap the lines of JTextArea we need to call the setLineWrap(boolean wrap) method and pass a true boolean value as the parameter. The setWrapStyleWord(boolean word) method wrap the lines at word boundaries when we set it to true.

package org.kodejava.swing;

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

public class TextAreaWrapDemo extends JPanel {
    public TextAreaWrapDemo() {
        initializeUI();
    }

    public static void showFrame() {
        JPanel panel = new TextAreaWrapDemo();
        panel.setOpaque(true);

        JFrame frame = new JFrame("JTextArea Demo");
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setContentPane(panel);
        frame.pack();
        frame.setVisible(true);
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(TextAreaWrapDemo::showFrame);
    }

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(500, 200));

        JTextArea textArea = new JTextArea(5, 40);

        String text = """
                The quick brown fox jumps over the lazy dog. \
                The quick brown fox jumps over the lazy dog. \
                The quick brown fox jumps over the lazy dog.
                """;

        textArea.setText(text);
        textArea.setFont(new Font("Arial", Font.BOLD, 18));

        // Wrap the lines of the JTextArea if it does not fit in the
        // current allocated with of the JTextArea.
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

JTextArea Wrap Text Line Demo

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.