JTabbedPane is a useful Swing container that provides a set of mutually exclusive tabs for accessing multiple components , as shown in Figure 28.20.
Usually you place the panels inside a JTabbedPane and associate a tab with each panel. JTabbedPane is easy to use, because the selection of the panel is handled automatically by clicking the corresponding tab. You can switch between a group of panels by clicking on a tab with a given title and/or icon. Figure 28.21 shows the frequently used properties, constructors, and methods in JTabbedPane .
Listing 28.10 gives an example that uses a tabbed pane with four tabs to display four types of figures: line, rectangle, rounded rectangle, and oval. You can select a figure to display by clicking the corresponding tab, as shown in Figure 28.20. The FigurePanel class for displaying a figure was presented in §13.7, "Case Study: The FigurePanel Class." You can use the type property to specify a figure type.
1 import java.awt.*; 2 import javax.swing.*; 3 4 public class DisplayFigure extends JApplet { 5 private JTabbedPane jtpFigures = new JTabbedPane(); 6 private FigurePanel squarePanel = new FigurePanel(); 7 private FigurePanel rectanglePanel = new FigurePanel(); 8 private FigurePanel circlePanel = new FigurePanel(); 9 private FigurePanel ovalPanel = new FigurePanel(); 10 11 public DisplayFigure() { 12 squarePanel.setType(FigurePanel.LINE); 13 rectanglePanel.setType(FigurePanel.RECTANGLE); 14 circlePanel.setType(FigurePanel.ROUND_RECTANGLE); 15 ovalPanel.setType(FigurePanel.OVAL); 16 17 add(jtpFigures, BorderLayout.CENTER); 18 jtpFigures.add(squarePanel, "Line" ); 19 jtpFigures.add(rectanglePanel, "Rectangle" ); 20 jtpFigures.add(circlePanel, "Round Rectangle" ); 21 jtpFigures.add(ovalPanel, "Oval" ); 22 23 jtpFigures.setToolTipTextAt( , "Line" ); 24 jtpFigures.setToolTipTextAt( 1 , "Rectangle" ); 25 jtpFigures.setToolTipTextAt( 2 , "Round Rectangle" ); 26 jtpFigures.setToolTipTextAt( 3 , "Oval" ); 27 } 28 } |
The program creates a tabbed pane to hold four panels, each of which displays a figure. A panel is associated with a tab. The tabs are titled Line, Rectangle, Rounded Rectangle, and Oval.
By default, the tabs are placed at the top of the tabbed pane. You can select a different placement using the tabPlacement property.