The JTabbedPane Class

The tabbed pane is now a fixture in applications for option displays, system configuration displays and other multiscreen UIs. In the AWT, you have access to the CardLayout layout manager, which can be used to simulate the multiscreen behavior, but it contains nothing to graphically activate screen switching—you must write that yourself. Figure 11.7 shows that with the JTabbedPane, you can create your own tabbed pane, with tab activation components, very quickly.

A simple tabbed pane with three tabs in Metal, Windows, and Motif look-and-feels

Figure 11-7. A simple tabbed pane with three tabs in Metal, Windows, and Motif look-and-feels

Here’s the code that generated this simple application. We use the tabbed pane as our real container and create new tabs using the addTab() method. Note that each tab can contain exactly one component. As with a CardLayout-managed container, you quite often add a container as the one component on the tab. That way, you can then add as many other components to the container as necessary.

// SimpleTab.java
            
             // A quick test of the JTabbedPane component. // import java.awt.*; import java.util.*; import java.awt.event.*; import javax.swing.*; public class SimpleTab extends JFrame { JTabbedPane jtp; public SimpleTab() { super("JTabbedPane"); setSize(200, 200); Container contents = getContentPane(); jtp = new JTabbedPane(); jtp.addTab("Tab1", new JLabel("This is Tab One")); jtp.addTab("Tab2", new JButton("This is ...

Get Java Swing now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.