The CardLayout constitutes a more enhanced manager that can group multiple containers in the form of cards each showing a time, or that is, only one container at a time is visible. This layout manager is based on the idea of the tabs. Each container can have its layout specific, allowing different layout managers are used in a same window space.
We usually serve some sort of event to move from one component to another. As seems logical, it may be appropriate in many cases to know what the previous and next component, which is why this layout manager provides some own methods:
• public CardLayout()
• public CardLayout(int hgap, int vgap)
• void first(Container parent)
• public void last(Container parent)
• public void next(Container parent)
• public void previous(Container parent)
• public void show(Container parent, String name)
It is essential to know the layout of the parent Container. To add components to a Container using this layout manager we use the method.
void add(Component to, String name)
The name parameter identifies the components and is the same name as a parameter to pass on the show (…) method.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class CardLayoutJavaExample extends JFrame implements ActionListener
{
private CardLayout cards = new CardLayout();
private JButton BtnWalking = new JButton("The Walking Dead");
private JButton BtnGalactic = new JButton("Galactic Phantasy Prelude");
private JButton BtnFarm = new JButton("Farm Heroes Saga");
public CardLayoutJavaExample()
{
setLayout(cards);
add("Dead", BtnWalking);
BtnWalking.addActionListener(this);
add("Galactic", BtnGalactic);
BtnGalactic.addActionListener(this);
add("Farm", BtnFarm);
BtnFarm.addActionListener(this);
setSize(250, 150);
setVisible(true);
}
public void actionPerformed(ActionEvent e)
{
cards.next(getContentPane());
}
public static void main(String[] args)
{
CardLayoutJavaExample frame = new CardLayoutJavaExample();
}
}