How can you hide the tab in Java Swing JTabbedPane?

21 views Asked by At

In my code, I set Laptop to .setSelectedIndex(0); as the default tab. In addition, with the Laptop tab set as the default tab, users want the Laptop tab to be hidden.

package test;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class JTabbedPanel {
    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;
        JButton button1 = new JButton("Press Me");
        button1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent arg0) {
                System.out.println("It still works");
            }
        });
        panel1 = new JPanel();
        panel1.add(button1);
        panel2 = new JPanel();
        panel2.add(text);
        panel3 = new JPanel();

        tabbedPane.addTab("Laptop", panel1);
        tabbedPane.addTab("Desktop", panel2);
        tabbedPane.addTab("Notebook", panel3);
        tabbedPane.setSelectedIndex(0);

        
        //tabbedPane.removeTabAt(0);

        frame.add(tabbedPane);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(550, 350);
        frame.setVisible(true);
    }
}

So I'm tabbedPane.removeTabAt(0); I expected to hide the Laptop panel with , The Laptop panel is hidden, but I can't see the Laptop panel I set as default. My laptop panel is set to the default and when I run the initial program The Laptop panel looks like the default, so I want to see the button I want the Laptop panel itself to be hidden from the user.

1

There are 1 answers

0
Piyush Baghel On

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