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

    private void initializeUI() {
        JTabbedPane pane = new JTabbedPane();
        pane.addChangeListener(this);

        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();
        panel.setOpaque(true);

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

    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() {
                TabbedPaneSelection.showFrame();
            }
        });
    }
}