Java AWT | CardLayout Class
The CardLayout class manages the components in such a way that only one component is visible at a time. It treats each component as a card in the container. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- CardLayout(): It is used to create a new card layout with gaps of size is zero.
- CardLayout(int horizontalgap, int verticalgap): It is used to create a new CardLayout class with the specified horizontal and vertical gaps.
Commonly Used Methods:
- getLayoutAlignmentX(Container parent): Returns the alignment along the x-axis.
- getLayoutAlignmentY(Container parent): Returns the alignment along the y-axis.
- getVgap(): Used to get the vertical gap between components.
- addLayoutComponent(Component cm, Object cn): Used to add the specified component to this card layout’s internal table of names.
- getHgap(): Used to get the horizontal gap between components.
- toString(): Returns a string representation of the state of this card layout.
- removeLayoutComponent(Component cm): Used to remove the specified component from the layout.
Below programs illustrate the CardLayout class:
- Program 1: In the below program we are arranging several JLabel components in a JFrame, whose instance class is “Cardlayout“. We create 3 JButton components named “bt1“, “bt2“, “bt3” and then add them to the JFrame by the using add() method. We set the size and visibility of the frame by method setSize() and setVisible(). The layout is set by the method setLayout() method.
- Program 2: In below program we are arranging 4 JLabel components in a JFrame, whose class “CardlayoutDemo“. We create 4 JButton components named “firstbtn“, “nextbtn“, “previousbtn“, “lastbtn” and 4 JLabel components named “jl1“, “jl2“, “jl3” “jl4“. Here we are also creating 4 JPanel components named as “jp1“, “jp2“, “jp3“, “jp4” and then add them to the JFrame by the using add() method. We will set the size, visibility and title of the frame by using setSize(), setVisible() and setTitle() method respectively. The layout is set by using setLayout() method.
Note: The above programs might not run in an online IDE. Please use an offline compiler.