How do I insert a text in a specified position in JTextArea?

The insert(String str, int pos) of the JTextArea allows us to insert a text at the specified position. In the example below we insert brown and over words into the current JTextArea text.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaInsertText();
        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(TextAreaInsertText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick fox jumps the lazy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.insert("brown ", 10);
        textArea.insert("over ", 26);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The screenshot of the result from the code snippet above is:

JTextArea Insert Text Demo

How do I replace text in the JTextArea?

In this example you’ll see how to use the replaceRange(String str, int start, int end) method to replace a string in the JTextArea from the start position to the end position with the specified string.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaReplaceText();
        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(TextAreaReplaceText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick white fox jumps over the sleepy dog.";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        textArea.replaceRange("brown", 10, 15);
        textArea.replaceRange("lazy", 35, 41);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The screenshot of the code snippet above is:

JTextArea Replace Text Demo

How do I select all text in JTextArea?

Selecting all text in the JTextArea component can be done by using the selectAll() method. In the example below we use a button action to do the selection. After select the text we transfer focus back to the JTextArea so that the highlighted text is shown.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaSelectAll();
        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(TextAreaSelectAll::showFrame);
    }

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

        final JTextArea textArea = new JTextArea(
                "The quick brown fox jumps over the lazy dog.");
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        final JButton button1 = new JButton("Select All");
        button1.addActionListener(e -> {
            textArea.selectAll();

            // Transfer focus to JTextArea to show the selected
            // text.
            button1.transferFocusBackward();
        });
        final JButton button2 = new JButton("Get Selected Text");
        button2.addActionListener(e -> {
            String text = textArea.getSelectedText();
            System.out.println("Text = " + text);
        });

        JPanel buttonPanel = new JPanel(new FlowLayout());
        buttonPanel.add(button1);
        buttonPanel.add(button2);

        this.add(pane, BorderLayout.CENTER);
        this.add(buttonPanel, BorderLayout.SOUTH);
    }
}

And here the screenshot of the code snippet above:

JTextArea Select All Text

How do I append text to JTextArea?

To append text to the end of the JTextArea document we can use the append(String str) method. This method does nothing if the document is null or the string is null or empty.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaAppendText();
        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(TextAreaAppendText::showFrame);
    }

    private void initializeUI() {
        String text = "The quick brown fox ";

        JTextArea textArea = new JTextArea(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);
        JScrollPane scrollPane = new JScrollPane(textArea);

        String appendText = "jumps over the lazy dog.";
        textArea.append(appendText);

        this.setPreferredSize(new Dimension(500, 200));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }
}

The output of the code snippet above is:

JTextArea Append Text Demo

How do I set and get the contents of JTextArea?

To set and get the contents of a JTextArea you can use the setText(String text) and getText() methods. In the code below we create a JTextArea and sets its contents after we create a new instance of JTextArea. To get the contents we use the action on a button. When the button is pressed the contents of the JTextArea is read using the getText() method. This method return a String object.

package org.kodejava.swing;

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaGetContent();
        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(TextAreaGetContent::showFrame);
    }

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

        final JTextArea textArea = new JTextArea();

        // Set the contents of the JTextArea.
        String text = "The quick brown fox jumps over the lazy dog.";
        textArea.setText(text);
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        JScrollPane pane = new JScrollPane(textArea);
        pane.setPreferredSize(new Dimension(500, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JButton button = new JButton("Get Contents");
        button.addActionListener(e -> {
            // Get the contents of the JTextArea component.
            String contents = textArea.getText();
            System.out.println("contents = " + contents);
        });

        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
    }
}

The output of the code snippet above is:

Set and Get the Content of JTextArea