Java Reference
In-Depth Information
2.
Next, an additional panel is created to hold a JComboBox , which has the same strings used for the
names of the panels (“ BLUE PANEL ” and “ RED PANEL ”) included here as items. Some additional
code adds an item listener, which is necessary to make the combobox actually do something when
selecting an item. Don't worry about the details yet, as you will see much more about listeners
when you read about GUI events. Just note for now that this code gets the CardLayout object from
the cards JPanel and then instructs this layout manager to show a card in the cardPanel with a
given string identifier.
3.
The TabbedFrame version is somewhat simpler. Here, a single JTabbedPane component is
set up and added to the JFrame . Now, you can directly add your two colored panels, and the
JTabbedPane component handles everything else for you.
In the Try It Out, the most important line is the one that gets the CardLayout layout manager to
show another card:
CardLayout cl = (CardLayout)(cardPanel.getLayout());
cl.show(cardPanel, (String)evt.getItem());
There are a few other helpful methods you can call for a CardLayout object:
first (Container parentContainer) : Show the first card of the container.
next (Container parentContainer) : Show the next card of the container or flip back to
the first one when the end is reached.
previous (Container parentContainer) : Show the previous card or flip to the last one
when the beginning is reached.
last (Container parentContainer) : Show the last card of the container.
show (Container parentContainer, String name) : Show the card that was added
to the container with the given specific name (this is the one used in the Try It Out
example).
In general, you'll not see the CardLayout used that often, especially since components such as
JTabbedFrame allow you to accomplish the same with less boilerplate code (showing how many
cards exist, handling switching between cards, and so on).
Boxlayout
BoxLayout is another layout manager that's relatively simple to use. Put simply, BoxLayout will
stack components on top of each other or place them in a row. Therefore, you can think of it as a
version of the FlowLayout layout manager, but with greater functionality.
There's only one constructor available:
public BoxLayout(Container target, int axis);
 
Search WWH ::




Custom Search