Java


Java Tutorial


Admission Enquiry Form

  

Java CardLayout

Java CardLayout

A Card layout is a group of containers or components that are displayed one at a time.Each container in the group ia called a card.

Constructors of CardLayout class

Type of Constructor Constructor Description
CardLayout() It creates a card layout with zero horizontal and vertical gap.
CardLayout(int hgap, int vgap) It creates a card layout with the given horizontal and vertical gap.


Basic Methods of CardLayout class :

Method NameDescription
public void first(Container parent)This method is used to flip to the first card of the given container.
public void last(Container parent)This method is is used to flip to the last card of the given container.
public void next(Container parent)This method is used to flip to the next card of the given container.
public void previous(Container parent)This method is used to flip to the previous card of the given container.
public void show(Container parent, String name)This method is used to flip to the specified card with the given name.
getVgap()This method is used to get the vertical gap between components.
getHgap()This method is used to get the horizontal gap between components.



Example of CardLayout with ActionListener

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

class CardLayoutDemo extends JFrame implements ActionListener
{
CardLayout card;
JButton b1, b2, b3;
Container c1;
CardLayoutDemo()
{
c1= getContentPane();
card = new CardLayout(40, 30);
//create CardLayout object with 40 hor space and 30 ver space
c1.setLayout(card);
b1 = new JButton("First Card");
b2 = new JButton("Second Card");
b3 = new JButton("Third Card");
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c1.add("1", b1);
c1.add("2", b2);
c1.add("3", b3);
setTitle("CardLayout Demo");
setSize(300,300);
setVisible(true);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
public void actionPerformed(ActionEvent e)
{
card.next(c1);
}
}
public class CardLayoutEx
{
public static void main(String[] args)
{
CardLayoutDemo ex=new CardLayoutDemo();
}
}

Output

The code above will display :