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() {
        initializeUI();
    }

    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(300, 100));
        this.setLayout(new BorderLayout());
        this.add(scrollPane, BorderLayout.CENTER);
    }

    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(new Runnable() {
            public void run() {
                TextAreaReplaceText.showFrame();
            }
        });
    }
}

How do I set and get the contents of JTextArea?

To set and get the contents of 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.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 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(400, 200));
        pane.setVerticalScrollBarPolicy(
                JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        JButton button = new JButton("Get Contents");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent 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);
    }

    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(new Runnable() {
            public void run() {
                TextAreaGetContent.showFrame();
            }
        });
    }
}

How do I set the tab size in JTextArea?

In this example you will be shown how to set or change the tab size for the JTextArea component. You can use the setTabSize(int size) to define the tab size. For this demo we create a combo box that have some integer values which will be use to define the tab size. When you change the selected item in the combo box the JTextArea tab size will be change immediately.

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

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

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

        JLabel label = new JLabel("Tab size: ");
        Object[] items = {2, 4, 8, 10, 20};
        final JComboBox comboBox = new JComboBox(items);

        JPanel tabPanel = new JPanel(new FlowLayout());
        tabPanel.add(label);
        tabPanel.add(comboBox);

        this.add(tabPanel, BorderLayout.NORTH);

        final JTextArea textArea = new JTextArea();
        textArea.setLineWrap(true);
        textArea.setWrapStyleWord(true);

        //
        // Sets the number of characters to expand tabs to.
        //
        textArea.setTabSize((Integer) comboBox.getSelectedItem());
        comboBox.addItemListener(new ItemListener() {
            public void itemStateChanged(ItemEvent e) {
                textArea.setTabSize((Integer) comboBox.getSelectedItem());
            }
        });

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

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

    public static void showFrame() {
        JPanel panel = new TextAreaSetTabSize();
        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(new Runnable() {
            public void run() {
                TextAreaSetTabSize.showFrame();
            }
        });
    }
}

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

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

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

    private void initializeUI() {
        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 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);
    }

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

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

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

How do I create a JTextArea?

This example shows you how to create a simple JTextArea component in Java Swing application. First you’ll create an instance of JTextAread and passes the number of rows and columns. Next to add a scroll ability you can wrap the component inside a JScrollPane.

package org.kodejava.example.swing;

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

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

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

        //
        // Creates a JTextArea with 5 rows and 40 colums. Then
        // wrap the JTextArea inside a JScrollPane for adding
        // scrolling abilities.
        //
        JTextArea textArea = new JTextArea(5, 40);
        JScrollPane scrollPane = new JScrollPane(textArea);

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

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

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

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

How do I create an uneditable JTextArea?

The following example shows you how to set the property of the JTextArea so that it cannot be edited or modified. To make the JTextArea not editable call the setEditable() method and pass a false value as the parameter.

package org.kodejava.example.swing;

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

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

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

        JTextArea textArea = new JTextArea(5, 40);
        textArea.setText("The quick brown fox jumps over the lazy dog.");

        //
        // By default the JTextAread is editable, calling
        // setEditable(false) produce uneditable JTextArea.
        //
        textArea.setEditable(false);
        JScrollPane scrollPane = new JScrollPane(textArea);

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

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

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

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

How do I set the font and color of JTextArea?

To set the font and color of JTextArea we can use the setFont() and setForeground() methods of the JTextArea. To create a font we must define the font name, the font style and its size. For the colors we can uses the constant color values defined by the Color class.

package org.kodejava.example.swing;

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

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

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

        JTextArea textArea = new JTextArea(5, 40);
        textArea.setLineWrap(true);
        textArea.setText("The quick brown fox jumps over the lazy dog.");

        // Sets JTextArea font and color.
        Font font = new Font("Segoe Script", Font.BOLD, 20);
        textArea.setFont(font);
        textArea.setForeground(Color.BLUE);
        JScrollPane scrollPane = new JScrollPane(textArea);

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

    private static void showFrame() {
        JPanel panel = new TextAreaFontDemo();
        panel.setOpaque(true);

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

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

Here is the program screenshot of the code snippet above:

JTextArea Font and Color

How do I remove tabs from JTabbedPane?

To remove tabs from JTabbedPane we can use the following remove methods:

  • remove(int index) method to remove a tab at the specified index.
  • remove(Component component) method to remove a tab that has the specified child component.
  • removeAll() method to remove all tabs.

 

package org.kodejava.example.swing;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

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

    private void initializeUI() {
        final JTabbedPane pane = new JTabbedPane(JTabbedPane.LEFT);
        pane.addTab("A Tab", new JPanel());
        pane.addTab("B Tab", new JPanel());

        JPanel tabPanel = new JPanel();
        pane.addTab("C Tab", tabPanel);
        pane.addTab("D Tab", new JPanel());
        pane.addTab("E Tab", new JPanel());

        //
        // Remove the last tab from JTabbedPane
        //
        pane.remove(pane.getTabCount() - 1);

        //
        // Remove tab that contains a tabPanel component which is
        // the C Tab.
        //
        pane.remove(tabPanel);

        JButton button = new JButton("Remove All Tabs");
        button.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                //
                // Remove all tabs from JTabbedPane
                //
                pane.removeAll();        
            }
        });

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));
        this.add(pane, BorderLayout.CENTER);
        this.add(button, BorderLayout.SOUTH);
    }

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

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

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

How do I assign tool tips for JTabbedPane tabs?

To set a tool tips for JTabbedPane‘s tabs you need to pass the tool tips when adding a new tab to the JTabbedPane. The addTab() method accept the following parameters: the tab’s title, image icon, a component that is going to be the content of the tabs and a string of tool tips information.

When you hover your mouse to the JTabbedPane‘s tabs the tool tips will be shown on the screen. Here is an example how you can can add tool tips the JTabbedPane‘s tabs.

package org.kodejava.example.swing;

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

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

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

        JTabbedPane pane = new JTabbedPane();
        ImageIcon tab1Icon = new ImageIcon(
                this.getClass().getResource("/tab1.png"));
        ImageIcon tab2Icon = new ImageIcon(
                this.getClass().getResource("/tab2.png"));
        ImageIcon tab3Icon = new ImageIcon(
                this.getClass().getResource("/tab3.png"));

        JPanel content1 = new JPanel();
        JPanel content2 = new JPanel();
        JPanel content3 = new JPanel();

        //
        // Add tabs to the JTabbedPane. The last parameter in the
        // add tab method is the tool tips for the tabs.
        //
        pane.addTab("Pool", tab1Icon, content1,
                "Pool Game Board");
        pane.addTab("Basketball", tab2Icon, content2,
                "Basketball Game Board");
        pane.addTab("Football", tab3Icon, content3,
                "Football Game Board");

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

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

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

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

How do I disable or enable tabs in JTabbedPane?

To enable or disable tabs in JTabbedPane you can use the JTabbedPane‘s setEnableAt(int index, boolean enable) method. The index is zero based, this means that the first tab is at index number 0. The enable parameter when set to true will enable the tab while setting to false will disable the tab.

package org.kodejava.example.swing;

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

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

    private void initializeUI() {
        JTabbedPane pane = new JTabbedPane();
        pane.addTab("Tabs A", new JPanel());
        pane.addTab("Tabs B", new JPanel());
        pane.addTab("Tabs C", new JPanel());
        pane.addTab("Tabs D", new JPanel());

        //
        // Disable the first tab
        //
        pane.setEnabledAt(0, false);

        //
        // Disable the last tab, the pane.getTabCount() return the
        // number of tabs in the JTabbedPane. Because the index
        // start at 0 we need to subtract the count by 1.
        //
        pane.setEnabledAt(pane.getTabCount() - 1, false);

        this.setLayout(new BorderLayout());
        this.setPreferredSize(new Dimension(400, 200));
        this.add(pane, BorderLayout.CENTER);
    }

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

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

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

Below is the screenshot result of the code snippet above:

JTabbedPane Disable Enable Tab