What is the importance of the CardLayout class in Java?

The functionality of CardLayout arranges the components in a sequential manner and only one component is visible at one time and each component will be treated as one card.

CardLayout

• The CardLayout is different from the other layouts where the other layout managers attempt to display all the components within the container at once, the CardLayout displays only one component at a time.
• In the CardLayout, cards are usually placed in a container such as a JPanel. The components are placed into the card queue in the order in which they are added.
• The important methods of CardLayout are first(), last(), next(), previous() and show().

Example

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class CardLayoutTest extends JFrame implements ActionListener {
CardLayout card;
JButton b1,b2,b3;
Container con;
CardLayoutTest() {
con = this.getContentPane();
card = new CardLayout(40,30);
con.setLayout(card);
b1 = new JButton("Java");
b2 = new JButton("Python");
b3 = new JButton("Scala");
}
public void actionPerformed(ActionEvent e) {
card.next(con);
}

public static void main(String[] args) {
CardLayoutTest clt = new CardLayoutTest();
clt.setTitle("CardLayout Test");
clt.setSize(350, 275);
clt.setLocationRelativeTo(null);
clt.setDefaultCloseOperation(EXIT_ON_CLOSE);
clt.setVisible(true);
}
}

In the above example, we can use the CardLayout manager where only one component (Java) will be visible on the window. When we click on the window remaining components (Python and Scala) can be visible.

Output

Published on 10-Jul-2019 11:35:00