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.example.swing;

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

public class TextAreaReplaceText extends JPanel {
    public TextAreaReplaceText() {

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

        JTextArea textArea = new JTextArea(text);
        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);

    public static void showFrame() {
        JPanel panel = new TextAreaReplaceText();

        JFrame frame = new JFrame("JTextArea Demo");

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {

The screenshot of the code snippet above is:

JTextArea Replace Text Demo

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

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