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

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

public class TextAreaInsertText extends JPanel {
    public TextAreaInsertText() {

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

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

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

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

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

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

JTextArea Insert 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.