Java Swing How to - Call a certain function when click on a Tab








Question

We would like to know how to call a certain function when click on a Tab.

Answer

import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
/* www .j a  va  2  s. c o  m*/
public class Main {

  public static void main(String[] args) {
    JFrame f = new JFrame();
    f.setSize(800, 600);
    f.setLocationRelativeTo(null);

    JTabbedPane p = new JTabbedPane();
    p.addTab("T1", new JPanel());
    p.addTab("T2", new JPanel());
    p.addTab("T3", new JPanel());

    p.addChangeListener(e -> {
      System.out.println("" + p.getSelectedIndex());
      // Index starts at 0, so Index 2 = Tab3
      if (p.getSelectedIndex() == 2) {
        // do your stuff on Tab 3
      }
    });
    f.add(p);
    f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    f.setVisible(true);
  }
}