Tab panels in action

Tab panels can be used to create a user interface. Lee Chuk-Munn goes into detail.

The tab panel is a popular way to create a user interface; by using tab panels, you can logically partition user interfaces and present them in a single window. This paradigm has been used in popular applications like the Firefox browser to present different Web pages under a single window.

On the Java platform, you would use the JTabbedPane to create tab panels. However, unlike the tab in Firefox, which presents a button to close a particular tab (see figure), there is no intuitive way to close a tab created by JTabbedPane.


Tab in Firefox; note the button on the right to close the tab

Tabs created by JTabbedPane

Often you have to resort to creating a separate 'close tab' button somewhere in the window to achieve this.

In JavaSE 6, the next release of the JavaSE platform, you can now add a close button or any other Swing component to a tab by using setTabComponentAt() method. Using this method, you are basically responsible for rendering the title of a tab. Assuming we wish to create the following tab panel:


A tab panel with a standard JButton in each tab

Using this new feature, here is the code snippet to do this.

JTabbedPane tabPanel = new JTabbedPane();
//COLORS is an array of Strings
for (int i = 0; i < COLORS.length; i++) {
   //First create a new tab
   tabPanel.addTab(COLORS[i], new JPanel());
   //Create a panel to hold the COLOR and a JButton
   JPanel panel = new JPanel();
   JButton button = new JButton("X");
   button.addActionListener(this);
   panel.add(new JLabel(COLORS[i]));
   panel.add(button);
   //Add the panel to the current tab, override the default renderer
   tabPanel.setTabComponentAt(i, panel);
}

What else can we add to a tab besides a close button? Here are some ideas. Let's say you are developing a RPG game and you wish to allow the play to configure your party of four characters. What you can do is use the tab for character creation and the panel within the tab for setting character statistics. An example of this is shown below:


A RPG type game

To use the cliche, the possibilities are truly limitless. All the sources (and more) for the examples described in this article can be found in this zip file.

Lee Chuk-Munn has been programming in the Java language since 1996, when he first joined Sun Microsystems in Hong Kong. He currently works as a senior developer consultant and technology evangelist for Technology Outreach at Sun in Singapore. Chuk's focus is in Java APIs, Java EE, Java SE, and Java ME. Chuk graduated in 1987 from the Royal Melbourne Institute of Technology in Melbourne, Australia, where his favorite subject was compiler theory.