Enable and Disable Tab in Java

In this section you will learn how to enable and
disable any tab in a TabbedPane component of Java Swing. The tabbed pane
container can have one or more tables. All the tabs have a specific area in same
place. Whenever you will click on any tab, the components added to the tab will
be displayed. Sometimes it is necessary to disable some of the tabs. Following figure shows a frame
in which some tabs are disabled:

This program shows the multiple tabs on the frame.
These tabs have a suitable name and index number. To enable or disable any
tab you can use the setEnabledAt(int index,
Boolean value) function. Tabs are by
default enabled. Following are some methods and APIs that you can use in your
program to enable or disable the tabs.
addTab():
This is the method of JTabbedPane class, adds the tabs
to the
panel or other other container component. The parameter description of the
function are as follows:
- First is the title of the tab of string data type
- Second is the icon for the tab
- Third is the component which is displayed on the
corresponding tab
- And last is the tool tip text for the tab
setEnabledAt(int index, Boolean value):
This is the method of JTabbedPane class,
enables or disables the tab. This method takes two argument in which, first is the index
number of the tab which has to be enabled or disabled and another argument is
the boolean value. If the boolean value is TRUE then tab get enabled other wise
tab gets disabled.
Here is the code of program:
import javax.swing.*;
public class EnableAndDisableTab{
public static void main(String[] args) {
EnableAndDisableTab t = new EnableAndDisableTab();
}
public EnableAndDisableTab(){
JFrame frame = new JFrame("Enabling and Disabling a Tab in a JTabbedPane Container");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel panel = new JPanel();
JPanel panel1 = new JPanel();
JPanel panel2 = new JPanel();
JPanel panel3 = new JPanel();
JPanel panel4 = new JPanel();
JTabbedPane tpane = new JTabbedPane();
tpane.addTab("Index", null, panel, "This is enable.");
tpane.addTab("Table of contents", null, panel1, "This is disable.");
tpane.addTab("Types of colors", null, panel2, "This is enable.");
tpane.addTab("Types of computers", null, panel3, "This is disable.");
tpane.addTab("Category", null, panel4, "This is enable.");
tpane.setEnabledAt(1, false);
tpane.setEnabledAt(3,false);
frame.add(tpane);
frame.setSize(400,400);
frame.setVisible(true);
}
}
|
Download this example

|