java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to detect tab selection changes in JTabbedPane?

To detect the tab selection changes in JTabbedPane you must add a ChangeListener implementation to the instance of JTabbedPane. The stateChanged() method of this interface will be fired every time a new tab is selected. If you want to get the selected tab index you can use the JTabbedPane's getSelectedIndex() method.

package com.javacoderanch.example.swing;

import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
import java.awt.Dimension;
import java.awt.BorderLayout;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

public class TabbedPaneSelection extends JPanel 
        implements ChangeListener {
    public TabbedPaneSelection() {

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

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

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

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

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

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

    public void stateChanged(ChangeEvent e) {
        JTabbedPane pane = (JTabbedPane) e.getSource();
        int selectedIndex = pane.getSelectedIndex();
        System.out.println("selectedIndex = " + selectedIndex);

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