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

        JTabbedPane pane = new JTabbedPane();
        ImageIcon tab1Icon = new ImageIcon(
            this.getClass().getResource("/images/test-pass-icon.png"));
        ImageIcon tab2Icon = new ImageIcon(
            this.getClass().getResource("/images/test-fail-icon.png"));
        ImageIcon tab3Icon = new ImageIcon(
            this.getClass().getResource("/images/test-error-icon.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("Success", tab1Icon, content1,
            "Success Test Cases");
        pane.addTab("Fail", tab2Icon, content2,
            "Fail Test Cases");
        pane.addTab("Error", tab3Icon, content3,
            "Error Test Cases");

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

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

The result of the code snippet above is:

JTabbedPane Tabs’ Tool Tips Demo

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(500, 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:

Enable or Disable Tabs in JTabbedPane

How do I set the colors of JTabbedPane tabs?

The example below demonstrates how to change the color of the tabs in JTabbedPane component. The JTabbedPane‘s methods that you can use the change foreground and background color are:

  • setForeground(Color color) for changing the foreground color of all tabs.
  • setBackground(Color color) for changing the background color of all tabs.
  • setForegroundAt(int index, Color color) for changing foreground color for a tab at defined index.
  • setBackgroundAt(int index, Color color) for changing the background color of a tab at a defined index.
package org.kodejava.example.swing;

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

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

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

        JTabbedPane pane = new JTabbedPane();
        pane.addTab("A Tab", new JPanel());
        pane.addTab("B Tab", new JPanel());
        pane.addTab("C Tab", new JPanel());
        pane.addTab("D Tab", new JPanel());

        // Set all tabs foreground color to black.
        pane.setForeground(Color.BLACK);

        // Set different background color for all tabs in
        // JTabbedPane. The color from the first to the last
        // tab will be red, green yellow and orange.
        pane.setBackgroundAt(0, Color.RED);
        pane.setBackgroundAt(1, Color.GREEN);
        pane.setBackgroundAt(2, Color.YELLOW);
        pane.setBackgroundAt(3, Color.ORANGE);

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

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

The image below shows the result of the code snippet above:

JTabbedPane Tabs Color Demo

How do I add disabled icon for JTabbedPane tabs?

When adding a tabs to JTabbedPane you can define the icon for the tabs. This icon will be displayed beside the tab’s title in enable or disable state of the tabs. To make the user interface better you can also define a disabled icon for the tab. This icon will be displayed when the state of the tabs are disabled.

To assign a disabled icon for the tab use the JTabbedPane‘s setDisabledIconAt(int index, Icon icon) method. As always the index parameter is zero-based which means the first tab is at index number 0. The icon parameter is the disabled icon of your tabs.

package org.kodejava.example.swing;

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

public class TabbedPaneDisableIcon extends JPanel {
    private ImageIcon[] disableIcons = {
        new ImageIcon(
            this.getClass().getResource("/images/test-pass-icon-disable.png")),
        new ImageIcon(
            this.getClass().getResource("/images/test-fail-icon-disable.png")),
        new ImageIcon(
            this.getClass().getResource("/images/test-error-icon-disable.png")),
    };

    public TabbedPaneDisableIcon() {
        initializeUI();
    }

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

        JTabbedPane pane = new JTabbedPane();

        ImageIcon tab1Icon = new ImageIcon(
            this.getClass().getResource("/images/test-pass-icon.png"));
        ImageIcon tab2Icon = new ImageIcon(
            this.getClass().getResource("/images/test-fail-icon.png"));
        ImageIcon tab3Icon = new ImageIcon(
            this.getClass().getResource("/images/test-error-icon.png"));

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

        pane.addTab("Success", tab1Icon, content1);
        pane.addTab("Fail", tab2Icon, content2);
        pane.addTab("Error", tab3Icon, content3);

        for (int i = 0; i < pane.getTabCount(); i++) {
            pane.setDisabledIconAt(i, disableIcons[i]);
        }

        // Disable the last tab to see the disabled icon displayed.
        pane.setEnabledAt(pane.getTabCount() - 1, false);

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

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

The result of the code snippet above is:

Set Disabled Icon for JTabbedPane Tabs

How do I add icon to JTabbedPane tabs?

The following code snippet demonstrates how to create a JTabbedPane component with image icons attached on their tabs. There are two steps that we need to do to achieve this. First we need to load the image icon and after that we need to attach these icons to the tabs.

To create or load an image icon simply create an instance of ImageIcon class. Pass the information about the image location to the constructor of the ImageIcon. In the example below I provide the location of the image using the getClass().getResource() method which will load the images from resources directory.

To add a new tab with image icon attached to the tabs of a JTabbedPane component we are using the addTab(String, Icon, Component) method. The second argument in this method is the image icon of the tab.

Let’s see the code snippet below:

package org.kodejava.example.swing;

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

public class TabbedPaneWithIcon extends JPanel {
    private TabbedPaneWithIcon() {
        initializeUI();
    }

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

        JFrame frame = new JFrame("Tabbed Pane With Icon 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() {
                TabbedPaneWithIcon.showFrame();
            }
        });
    }

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

        JTabbedPane pane = new JTabbedPane();

        ImageIcon tab1Icon = new ImageIcon(
            this.getClass().getResource("/images/test-pass-icon.png"));
        ImageIcon tab2Icon = new ImageIcon(
            this.getClass().getResource("/images/test-fail-icon.png"));
        ImageIcon tab3Icon = new ImageIcon(
            this.getClass().getResource("/images/test-error-icon.png"));

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

        pane.addTab("Pass", tab1Icon, content1);
        pane.addTab("Fail", tab2Icon, content2);
        pane.addTab("Error", tab3Icon, content3);

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

The directory structure of the project:

kodejava-swing
├── pom.xml
└── src
    └── main
        ├── java
        │   └── org
        │       └── kodejava
        │           └── example
        │               └── swing
        │                   └── TabbedPaneWithIcon.java
        └── resources
            └── images
                ├── test-error-icon.png
                ├── test-fail-icon.png
                └── test-pass-icon.png

And here is the result of the code snippet above.

JTabbedPane Tab with Icon Demo

How do I scroll or wrap JTabbedPane tab layout?

JTabbedPane component tab layout policy of can be either set to JTabbedPane.SCROLL_TAB_LAYOUT or JTabbedPane.WRAP_TAB_LAYOUT. This layout policy will control the display of the tabs when the tabs cannot be displayed in one go. By the default the layout policy is set to JTabbedPane.WRAP_TAB_LAYOUT. Changing tab layout policy to JTabbedPane.SCROLL_TAB_LAYOUT makes the tabs scrollable. A button for scrolling left-right or up-down will be displayed in the tabbed pane.

package org.kodejava.example.swing;

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

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

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

        JFrame frame = new JFrame("TabbedPane Tab Layout Policy 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() {
                TabbedPaneTabLayoutPolicy.showFrame();
            }
        });
    }

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

        // Creates a JTabbedPane with scroll tab layout policy
        JTabbedPane pane = new JTabbedPane(JTabbedPane.TOP,
            JTabbedPane.SCROLL_TAB_LAYOUT);
        pane.addTab("One", createPanel("One"));
        pane.addTab("Two", createPanel("Two"));
        pane.addTab("Three", createPanel("Three"));
        pane.addTab("Four", createPanel("Four"));
        pane.addTab("Five", createPanel("Five"));
        pane.addTab("Six", createPanel("Six"));
        pane.addTab("Seven", createPanel("Seven"));
        pane.addTab("Eight", createPanel("Eight"));
        pane.addTab("Nine", createPanel("Nine"));
        pane.addTab("Ten", createPanel("Ten"));

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

    private JPanel createPanel(String title) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(new JLabel(title), BorderLayout.NORTH);
        return panel;
    }
}

Here is the screenshot of the code snippet created above. You can see that a button at the top right of the tabbed pane is added so that you can scroll to navigate the hidden tabs.

JTabbedPane Tab Layout Policy Demo

How do I change JTabbedPane tab placement position?

By default the tabs in a JTabbedPane component is placed on the top. But you can place the tabs on every side of the JTabbedPane component, for example it can be on the top, on the right, on the left or on the bottom of the JTabbedPane.

To change the tab placement position you need to set the tab placement when creating an instance of JTabbedPane. The tab placement can be set using the following constant values: JTabbedPane.TOP, JTabbedPane.RIGHT, JTabbedPane.LEFT and JTabbedPane.BOTTOM.

Let’s see the following code snippet to demonstrate it.

package org.kodejava.example.swing;

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

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

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

        JFrame frame = new JFrame("Tabbed Pane Tab Placement 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() {
                TabbedPaneTabPlacement.showFrame();
            }
        });
    }

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

        // Creates a JTabbedPane with tabs at the bottom.
        JTabbedPane pane = new JTabbedPane(JTabbedPane.BOTTOM);
        pane.addTab("Tab 1", createPanel("Panel 1"));
        pane.addTab("Tab 1", createPanel("Panel 2"));
        pane.addTab("Tab 3", createPanel("Panel 3"));

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

    private JPanel createPanel(String title) {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        panel.add(new JLabel(title), BorderLayout.NORTH);
        return panel;
    }
}

And here is the result of the code snippet above.

JTabbedPane Tab Position Demo

How do I detect tab selection changes in JTabbedPane?

In this example you will learn how to detect tab selection changes in a JTabbedPane component. To get notified when a tab is selected you must add a ChangeListener to the JTabbedPane component using the addChangeListener(). This method take an instance of class that implements the ChangeListener interface as it arguments.

In this example we implement the ChangeListener interface in the TabbedPaneSelection class. And we need to create an implementation for the stateChanged() method as defined by this interface contract. By implementing the interface in the TabbedPaneSelection class, we don’t need to create a separate class that specifically implement this interface. That’s why in the code snippet below we just pass the current object, using the this keyword, when calling the addChangeListener() method.

The stateChanged() method of this interface will be fired every time a new tab is selected. To get the selected tab index you can use the JTabbedPane‘s getSelectedIndex() method. The index returned by the getSelectedIndex() method is zero based, it means that if you select the first tab you will get index of 0, and if you select the second tab you will get index of 1.

package org.kodejava.example.swing;

import javax.swing.*;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import java.awt.*;

public class TabbedPaneSelection extends JPanel implements ChangeListener {
    public TabbedPaneSelection() {
        initializeUI();
    }

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

        JFrame frame = new JFrame("JTabbedPane Selection 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() {
                TabbedPaneSelection.showFrame();
            }
        });
    }

    private void initializeUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel dashboardPanel = new JPanel();
        tabbedPane.addTab("Dashboard", dashboardPanel);

        JPanel accountPanel = new JPanel();
        tabbedPane.addTab("Account", accountPanel);

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

        // Add ChangeListener to the tabbed pane.
        tabbedPane.addChangeListener(this);
    }

    public void stateChanged(ChangeEvent e) {
        JTabbedPane tabbedPane = (JTabbedPane) e.getSource();
        int selectedIndex = tabbedPane.getSelectedIndex();
        JOptionPane.showMessageDialog(null, "Selected Index: " + selectedIndex);
    }
}

If you run the presented code snippet above you’ll get the output as shown in the image below. And if you click the tab a message dialog will be displayed showing you the selected index.

JTabbedPane Selection Demo

How do I create a simple JTabbedPane?

In this example you will learn how to use JTabbedPane to arrange some components in tabbed view. The JTabbedPane component of the Swing API allows some components such as panels to share the same view. By selecting the corresponding tab, the panel will be displayed on the user’s screen. To add tabs to the JTabbedPane class you can use the addTab() method.

To the addTab() method accept two arguments, the title of the tab and the component you wish to display as the content of the tab. In the code snippet below we will use a simple panel as the content of the tab. You can also define an image icon for the tab which makes the program looks better. You can read it in this example:

Now, let’s create a simple example of JTabbedPane which has three tabs and the corresponding content, they are the Dashboard, Transaction and Account tabs. Below is an image that show how the screen will looks.

Simple JTabbedPane Demo

package org.kodejava.example.swing;

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

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

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

        JFrame frame = new JFrame("Simple Tabbed Pane 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() {
                SimpleTabbedPane.showFrame();
            }
        });
    }

    private void initializeUI() {
        JTabbedPane tabbedPane = new JTabbedPane();

        JPanel dashboardPanel = new JPanel();
        dashboardPanel.add(new JLabel("Dashboard"));

        // Add Dashboard Tab
        tabbedPane.addTab("Dashboard", dashboardPanel);

        JPanel transactionPanel = new JPanel();
        transactionPanel.add(new JLabel("Transaction"));

        // Add Transactions Tab
        tabbedPane.addTab("Transaction", transactionPanel);

        JPanel accountPanel = new JPanel();
        accountPanel.add(new JLabel("Account"));

        // Add Account Tab
        tabbedPane.addTab("Account", accountPanel);

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

How do I reverse JSlider’s value-range?

On a normal JSlider the value range displayed left-to-right on a horizontal JSlider and bottom-to-top on vertical JSlider. To reverse the slider values from their normal order you can use the setInverted() method of the JSlider instance. Passing a true boolean value into this method call reverse the values order.

package org.kodejava.example.swing;

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

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

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

        JSlider slider = new JSlider(JSlider.HORIZONTAL, 0, 20, 10);
        slider.setMinorTickSpacing(1);
        slider.setMajorTickSpacing(5);
        slider.setPaintLabels(true);
        slider.setPaintTicks(true);

        // Reverse the value-range of a JSlider. On a normal
        // horizontal JSlider the maximum value is on the right
        // side. Specifying inverted to true makes the maximum
        // value placed on the left side.
        slider.setInverted(true);

        add(slider, BorderLayout.CENTER);
    }

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

        JFrame frame = new JFrame("Inverted JSlider");
        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() {
                JSliderInvertedDemo.showFrame();
            }
        });
    }
}

The result of the code snippet above is:

Inverted JSlider Demo