How to Use CardLayout in Java

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.

 

import java.awt.*;

import java.awt.event.*;

import javax.swing.*;

import java.util.*;

class cardlayout extends JApplet implements ActionListener

{

JPanel mp;

JPanel p1,p2;

JPanel b;

JButton b1,b2; //Two Buttons(b1 for card1 and b2 for card2)

CardLayout cl; //cardlayout object

JFrame jf;

cardlayout() //constructor

{

jf=new JFrame("CardLayout Demo");

mp=new JPanel();

cl=new CardLayout();

mp.setLayout(cl); //set main panel’s layout to be cardlayout

//creating two panels(card panels)to show

p1=new JPanel();

Date d1=new Date();

p1.add(new JLabel("   This is First Card "));

p1.add(new JLabel(d1.toString()));

p1.setBackground(Color.pink);

p2=new JPanel();

Date d=new Date();

p2.add(new JLabel("This is Second Card"));

p2.add(new JLabel(d.toString()));

p2.setBackground(Color.gray);

//creating two buttons and action listener

b1=new JButton("First");

b1.addActionListener(this);

b2=new JButton("Second");

b2.addActionListener(this);

//creating panel for adding buttons to it

b=new JPanel();

b.add(b1);

b.add(b2);

//setting layout for the applet to be borderlayout

jf.setLayout(new BorderLayout());

jf.add(b,BorderLayout.SOUTH);

jf.add(mp,BorderLayout.CENTER);

//adding two cards panels to the main panel container

mp.add(p1,"First");

mp.add(p2,"Second");

jf.setSize(300,300);

jf.setVisible(true);

}

//button clicks will respond by showing the name panel

public void actionPerformed(ActionEvent actionevnt)

{

if(actionevnt.getSource()==b1)

cl.show(mp,"First");

if(actionevnt.getSource()==b2)

cl.show(mp,"Second");

}

}

public class mycardlayout

{

public static void main(String aa[])

{

cardlayout cld=new cardlayout();

}

}

CardLayout in Java Swing

Explanation…

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.