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() {

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

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

        JPanel tabPanel = new JPanel(new FlowLayout());

        this.add(tabPanel, BorderLayout.NORTH);

        final JTextArea textArea = new JTextArea();

        // 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(500, 200));

        this.add(pane, BorderLayout.CENTER);

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

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

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

The output of the code snippet above is:

JTextArea Tab Size 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.