AJP Practical
AJP Practical
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.
Constructors:
1. CardLayout(): It is used to create a new card layout with gaps of size is zero.
2. 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.
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
Cardlayout()
{
card = new CardLayout(40, 30); // Initialization of object "card" of CardLayout class with 40 horizontal
space and 30 vertical space .
b1.addActionListener(this); // this Keyword refers to current object. Adding Jbutton "b1" on JFrame using
ActionListener.
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.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public CardLayoutDemo()
}});
} });
} } });
} } });