by Dinesh Thakur Category: Swing

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()
              add("Dead", BtnWalking);
              add("Galactic", BtnGalactic);
              add("Farm", BtnFarm);
              setSize(250, 150);
              public void actionPerformed(ActionEvent e)
                    public static void main(String[] args)
                            CardLayoutJavaExample frame = new CardLayoutJavaExample();

About Dinesh Thakur

Dinesh ThakurDinesh Thakur holds an B.C.A, MCSE, MCDBA, CCNA, CCNP, A+, SCJP certifications. Dinesh authors the hugely popular blog. Where he writes how-to guides around Computer fundamental , computer software, Computer programming, and web apps. For any type of query or something that you think is missing, please feel free to Contact us.

Related Articles