Java Swing How to - Disable and enable tabs in JTabbedPane








Question

We would like to know how to disable and enable tabs in JTabbedPane.

Answer

import java.awt.BorderLayout;
// w  w w  . j  a  v a 2s . c om
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.JTextArea;

public class Main {
  public Main() {
    JPanel jp = new JPanel();
    jp.setLayout(new BorderLayout());
    final JTabbedPane tb = new JTabbedPane();
    JButton btn = new JButton("push me !!!");
    btn.addActionListener(e -> {
      tb.setEnabledAt(1, true);
      tb.setEnabledAt(2, true);
      tb.setEnabledAt(3, true);
      tb.setEnabledAt(4, true);
    });
    JPanel pnl = new JPanel();
    pnl.add(btn);
    tb.add("Tab1", pnl);
    tb.add("Tab2", new JTextArea(10, 20));
    tb.add("Tab3", new JTextArea(10, 20));
    tb.add("Tab4", new JTextArea(10, 20));
    tb.add("Tab5", new JTextArea(10, 20));
    jp.add(tb, BorderLayout.CENTER);
    tb.setEnabledAt(1, false);
    tb.setEnabledAt(2, false);
    tb.setEnabledAt(3, false);
    tb.setEnabledAt(4, false);
    JFrame frame = new JFrame();
    frame.setLayout(new BorderLayout());
    frame.add(jp, BorderLayout.CENTER);
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.pack();
    frame.setVisible(true);
  }

  public static void main(String[] args) {
    Main tP = new Main();
  }
}