How do I find out which tab is selected on a JTabbedPane with a ChangeListener?

John Zukowski

Just attach a ChangeListener to the JTabbedPane. When selected, ask the event source (the pane) which index is selected. This is demonstrated below.


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

public class TabSample {
  static Color colors[] = {
    Color.red, 
    Color.orange, 
    Color.yellow, 
    Color.green, 
    Color.blue, 
    Color.magenta};
  static void add(JTabbedPane tabbedPane, String label) {
    int count = tabbedPane.getTabCount();
    JButton button = new JButton(label);
    button.setBackground(colors[count]);
    tabbedPane.addTab(label, null, button, label);
  }

  public static void main(String args[]) {

    JFrame frame = new JFrame("Tabbed Pane Sample");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    JTabbedPane tabbedPane = new JTabbedPane();
    String titles[] = {
      "General", 
      "Security", 
      "Content", 
      "Connection", 
      "Programs", 
      "Advanced"};
    for (int i=0, n=titles.length; i<n; i++) {
      add(tabbedPane, titles[i]);
    }

    ChangeListener changeListener = 
        new ChangeListener() {
      public void stateChanged(
          ChangeEvent changeEvent) {
        JTabbedPane sourceTabbedPane = 
          (JTabbedPane)changeEvent.getSource();
        int index = 
          sourceTabbedPane.getSelectedIndex();
        System.out.println (
          "Tab changed to: " + 
            sourceTabbedPane.getTitleAt(index));
      }
    };
    tabbedPane.addChangeListener(changeListener);

    Container contentPane = frame.getContentPane();
    contentPane.add(tabbedPane, BorderLayout.CENTER);
    frame.setSize(400, 150);
    frame.setVisible(true);
  }
}
0 Comments  (click to add your comment)
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact