Java Swing How to - Update JTabbedPane when new tab is added








Question

We would like to know how to update JTabbedPane when new tab is added.

Answer

import java.awt.BorderLayout;
/*from w w  w . ja va  2s.c o  m*/
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;

public class Main {
  public static final void main(String[] args) {
    JFrame frame = new JFrame();
    JTabbedPane tabbedPane = new JTabbedPane();

    frame.add(tabbedPane);

    JButton addButton = new JButton("Add tab");
    addButton.addActionListener(e -> {
      JPanel newTabComponent = new JPanel();
      int tabCount = tabbedPane.getTabCount();
      newTabComponent.add(new JLabel("I'm tab " + tabCount));
      tabbedPane.addTab("Tab " + tabCount, newTabComponent);
    });
    frame.add(addButton, BorderLayout.SOUTH);
    addButton.doClick();

    frame.setSize(800, 300);
    frame.setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
    frame.setVisible(true);
  }
}