Java Swing How to - Add new tab to JTabbedPane








Question

We would like to know how to add new tab to JTabbedPane.

Answer

import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.FlowLayout;
//  w  ww .j  a  v  a 2 s  . com
import javax.swing.JButton;
import javax.swing.JEditorPane;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;

public class Main {
  JTabbedPane tabbedPane = new JTabbedPane();
  JButton add = new JButton("Add Tab");
  int i = 1;
  public Main() {
    tabbedPane.add(new JScrollPane(createTabbedPanel()), "Tab " + i);
    add.addActionListener(e -> {
      i++;
      tabbedPane.add(new JScrollPane(createTabbedPanel()), "Tab " + i);
    });

    JFrame frame = new JFrame();
    JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING));
    buttonPanel.add(add);
    frame.add(buttonPanel, BorderLayout.PAGE_START);
    frame.add(tabbedPane);
    frame.pack();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
  }

  private JPanel createTabbedPanel() {
    JPanel panel = new JPanel(new BorderLayout());
    JTextField field = new JTextField(50);
    JEditorPane pane = new JEditorPane();
    pane.setPreferredSize(new Dimension(700, 500));

    panel.add(field, BorderLayout.NORTH);
    panel.add(pane, BorderLayout.CENTER);
    return panel;
  }
  public static void main(String[] args) {
    new Main();
  }
}