To enable or disable tabs in JTabbedPane
you can use the JTabbedPane
‘s setEnableAt(int index, boolean enable)
method. The index
is zero based, this means that the first tab is at index number 0
. The enable
parameter when set to true
will enable the tab while setting to false
will disable the tab.
package org.kodejava.swing;
import javax.swing.*;
import java.awt.*;
public class TabbedPaneEnableDisableTab extends JPanel {
public TabbedPaneEnableDisableTab() {
initializeUI();
}
public static void showFrame() {
JPanel panel = new TabbedPaneEnableDisableTab();
panel.setOpaque(true);
JFrame frame = new JFrame("JTabbedPane Demo");
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setContentPane(panel);
frame.pack();
frame.setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(TabbedPaneEnableDisableTab::showFrame);
}
private void initializeUI() {
JTabbedPane pane = new JTabbedPane();
pane.addTab("Tabs A", new JPanel());
pane.addTab("Tabs B", new JPanel());
pane.addTab("Tabs C", new JPanel());
pane.addTab("Tabs D", new JPanel());
// Disable the first tab
pane.setEnabledAt(0, false);
// Disable the last tab, the pane.getTabCount() return the
// number of tabs in the JTabbedPane. Because the index
// start at 0 we need to subtract the count by 1.
pane.setEnabledAt(pane.getTabCount() - 1, false);
this.setLayout(new BorderLayout());
this.setPreferredSize(new Dimension(500, 200));
this.add(pane, BorderLayout.CENTER);
}
}
Below is the screenshot result of the code snippet above:
Latest posts by Wayan (see all)
- How do I get number of each day for a certain month in Java? - September 8, 2024
- How do I get operating system process information using ProcessHandle? - July 22, 2024
- How do I sum a BigDecimal property of a list of objects using Java Stream API? - July 22, 2024