Java Reference
In-Depth Information
A card layout is created from the CardLayout class (in the java.awt package) with a
simple constructor:
CardLayout cc = new CardLayout();
The setLayout() method is used to make this the layout manager for the container, as in
the following statement:
setLayout(cc);
After you set a container to use the card layout manager, you must use a slightly differ-
ent add() method call to add cards to the layout.
The method to use is add( Component , String ) . The first argument specifies the con-
tainer or component that serves as a card. If it is a container, all components must have
been added to it before the card is added.
The second argument to the add() method is a string that represents the name of the
card. This can be anything you want to call the card. You might want to number the cards
in some way and use the number in the name, as in “Card 1” , “Card 2” , “Card 3” , and
so on.
The following statement adds a panel object named options to a container and gives this
card the name “Options Card” :
add(options, “Options Card”);
When a container using card layout is displayed for the first time, the visible card will be
the first card added to the container.
Subsequent cards can be displayed by calling the show() method of the layout manager,
which takes two arguments:
The container holding all the cards
n
The name of the card
n
The following statement calls the show() method of a card layout manager called cc :
cc.show(this, “Fact Card”);
The this keyword would be used in a frame or window governed by card layout—it
refers to the object inside which the cc.show() statement appears. “Fact Card” is the
name of the card to reveal. When a card is shown, the previously displayed card will be
obscured. Only one card in a card layout can be viewed at a time
In a program that uses the card layout manager, a card change will usually be triggered
by a user's action. For example, in a program that displays mailing addresses on different
cards, the user could select a card for display by selecting an item in a scrolling list.
Search WWH ::




Custom Search