142
Java CardLayout
The Java CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.
Constructors of CardLayout Class
- CardLayout(): creates a card layout with zero horizontal and vertical gap.
- CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.
Commonly Used Methods of CardLayout Class
- public void next(Container parent): is used to flip to the next card of the given container.
- public void previous(Container parent): is used to flip to the previous card of the given container.
- public void first(Container parent): is used to flip to the first card of the given container.
- public void last(Container parent): is used to flip to the last card of the given container.
- public void show(Container parent, String name): is used to flip to the specified card with the given name.
Example of CardLayout Class: Using Default Constructor
The following program uses the next() method to move to the next card of the container.
FileName: CardLayoutExample1.java
Output:
When the button named apple is clicked, we get
When the boy button is clicked, we get
Again, we reach the first card of the container if the cat button is clicked, and the cycle continues.
Example of CardLayout Class: Using Parameterized Constructor
FileName: CardLayoutExample2.java
Output:
Usage of the Methods of the CardLayout Class
The following example shows how one can use different methods of the CardLayout class.
FileName: CardLayoutExample3.java
Output:
Next TopicJava GridBagLayout