The CardLayout manager is used to manage a large number of components. It organizes the components in layers which are arranged like a deck of cards sharing the same display area such only one of them is visible at a time. In order to use card layout, it is required to create an object of type JPanel that will hold the cards.
class cardlayout extends JApplet implements ActionListener
JButton b1,b2; //Two Buttons(b1 for card1 and b2 for card2)
CardLayout cl; //cardlayout object
jf=new JFrame("CardLayout Demo");
mp.setLayout(cl); //set main panel’s layout to be cardlayout
//creating two panels(card panels)to show
Date d1=new Date();
p1.add(new JLabel(" This is First Card "));
Date d=new Date();
p2.add(new JLabel("This is Second Card"));
//creating two buttons and action listener
//creating panel for adding buttons to it
//setting layout for the applet to be borderlayout
//adding two cards panels to the main panel container
//button clicks will respond by showing the name panel
public void actionPerformed(ActionEvent actionevnt)
public class mycardlayout
public static void main(String aa)
cardlayout cld=new cardlayout();
JPanel mp… This is main panel which can hold the cards.
JPanel p1,p2…These panels will represent the cards.
JPanel b….This panel will hold buttons
In above example…
Here, a panel mp is created whose layout is set as cardlayout and is used for holding the other panels p1,p2. The panels p1 and p2 are used for holding the cards. The background color of p1 and p2 is set to pink and gray. Another panel named as b is created to hold two buttons namely, b1 and b2 Labeled as “First” AND “Second”. When b1 is clicked panel holding pink card is displayed and when b2 is clicked, panel holding the gray card is displayed.