Java Reference
In-Depth Information
3.
Try selecting a different panel from the drop‐down combobox. Notice how the blue panel changes
to make room for the red one and vice versa.
4.
You can also achieve the same effect by using a JTabbedPane Swing component instead of a
CardLayout layout manager. The following class shows how:
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
public class TabbedFrame {
public static void main(String[] args) {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setTitle("Tabbed frame");
JTabbedPane cardTabs = new JTabbedPane();
cardTabs.setPreferredSize(new Dimension(300, 400));
JPanel bluePanel = new JPanel();
JPanel redPanel = new JPanel();
bluePanel.setBackground(Color.blue);
redPanel.setBackground(Color.red);
cardTabs.add(bluePanel, "BLUE PANEL");
cardTabs.add(redPanel, "RED PANEL");
frame.getContentPane().add(cardTabs, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
}
}
5.
When you run the JTabbedPane version, you'll see
Figure 11-16.
How It Works
This is how it works:
1.
Note that the setup of this example is a bit more
complicated than the previous ones. First of all, the
layout manager for the content pane of the JFrame is
unchanged ( BorderLayout ). Next, a new JPanel is
created to store your “cards,” and its layout manager is
set to a CardLayout instance. Next, two colored cards
(also JPanels ) are created and added to the cardPanel .
The second argument of the add method, when using a
CardLayout , should be a string identifier for this card.
figure 11-16  
Search WWH ::




Custom Search