How to disable a Tab in a JTabbedPane Container with Java?

Java 8Object Oriented ProgrammingProgramming

To disable a tab in a JTabbedPane container, use the setEnabledAt() method and set it to false with the index of the tab you want to disable.

Let’s first create a JTabbedPane −

JTabbedPane tabbedPane = new JTabbedPane();

Now, let us disable a tab at index 2 −

tabbedPane.setEnabledAt(2, false);

The following is an example to disable a tab in a JTabbedPane Container −

Example

package my;
import javax.swing.*;
import java.awt.*;
public class SwingDemo {
   public static void main(String args[]) {
      JFrame frame = new JFrame("Devices");
      JTabbedPane tabbedPane = new JTabbedPane();
      JTextArea text = new JTextArea(100,100);
      JPanel panel1, panel2, panel3, panel4, panel5, panel6, panel7, panel8;
      panel1 = new JPanel();
      panel2 = new JPanel();
      panel2.add(text);
      panel3 = new JPanel();
      panel4 = new JPanel();
      panel5 = new JPanel();
      panel6 = new JPanel();
      panel7 = new JPanel();
      panel8 = new JPanel();
      tabbedPane.setBackground(Color.yellow);
      tabbedPane.setForeground(Color.black);
      tabbedPane.addTab("Laptop", panel1);
      tabbedPane.addTab("Desktop ", panel2);
      tabbedPane.addTab("Notebook", panel3);
      tabbedPane.addTab("Echo ", panel4);
      tabbedPane.addTab("Tablet", panel5);
      tabbedPane.addTab("Alexa ", panel6);
      tabbedPane.addTab("Notebook", panel7);
      tabbedPane.addTab("iPad", panel8);
      tabbedPane.setEnabledAt(2, false);
      tabbedPane.setEnabledAt(5, false);
      frame.add(tabbedPane);
      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      frame.setSize(550,350);
      frame.setVisible(true);
   }
}

The output is as follows. Here, we have disabled the tabs with index 2 and 5 −

raja
Published on 06-Jun-2019 09:04:19
Advertisements