Java Swing How to - Fire stateChanged event on JTabbedPane








Question

We would like to know how to fire stateChanged event on JTabbedPane.

Answer

import java.util.Date;
//  w w w .  j  a va2  s .co m
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.AncestorEvent;
import javax.swing.event.AncestorListener;

public class Main {

  private static JPanel createPanel() {
    JPanel panel = new JPanel();
    final JLabel label = new JLabel(new Date().toString());
    panel.add(label);
    panel.addAncestorListener(new AncestorListener() {
      @Override
      public void ancestorAdded(AncestorEvent event) {
        // start animation
        label.setText(new Date().toString());
      }

      @Override
      public void ancestorRemoved(AncestorEvent event) {
        // stop animation
      }

      @Override
      public void ancestorMoved(AncestorEvent event) {
      }
    });
    return panel;
  }

  public static void main(String[] args) {
    JFrame f = new JFrame();
    final JTabbedPane jtp = new JTabbedPane();
    jtp.add("One", createPanel());
    jtp.add("Two", createPanel());
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.add(jtp);
    f.pack();
    f.setVisible(true);
  }
}