Open In App

Java AWT | CardLayout Class

Last Updated : 17 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

The CardLayout class manages the components in such a way that only one component is visible 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.

Java




// Java program to illustrate the CardLayout Class
import java.awt.*;
import java.awt.event.*;
import javax.swing.JFrame;
import javax.swing.*;
 
// class extends JFrame and implements actionlistener
public class Cardlayout extends JFrame implements ActionListener {
 
    // Declaration of objects of CardLayout class.
    CardLayout card;
 
    // Declaration of objects of JButton class.
    JButton b1, b2, b3;
 
    // Declaration of objects
    // of Container class.
    Container c;
 
    Cardlayout()
    {
 
        // to get the content
        c = getContentPane();
 
        // Initialization of object "card"
        // of CardLayout class with 40
        // horizontal space and 30 vertical space .
        card = new CardLayout(40, 30);
 
        // set the layout
        c.setLayout(card);
 
        // Initialization of object "b1" of JButton class.
        b1 = new JButton("GEEKS");
 
        // Initialization of object "b2" of JButton class.
        b2 = new JButton("FOR");
 
        // Initialization of object "b3" of JButton class.
        b3 = new JButton("GEEKS");
 
        // this Keyword refers to current object.
        // Adding Jbutton "b1" on JFrame using ActionListener.
        b1.addActionListener(this);
 
        // Adding Jbutton "b2" on JFrame using ActionListener.
        b2.addActionListener(this);
 
        // Adding Jbutton "b3" on JFrame using ActionListener.
        b3.addActionListener(this);
 
        // Adding the JButton "b1"
        c.add("a", b1);
 
        // Adding the JButton "b2"
        c.add("b", b2);
 
        // Adding the JButton "b1"
        c.add("c", b3);
    }
     
    public void actionPerformed(ActionEvent e)
    {
         
        // call the next card
        card.next(c);
    }
 
    // Main Method
    public static void main(String[] args)
    {
         
        // Creating Object of CardLayout class.
        Cardlayout cl = new Cardlayout();
 
        // Function to set size of JFrame.
        cl.setSize(400, 400);
 
        // Function to set visibility of JFrame.
        cl.setVisible(true);
 
        // Function to set default operation of JFrame.
        cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
    }
}


Output: 

  • 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. 

Java




// Java program to show Example of CardLayout.
// in java. Importing different Package.
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
 
// class extends JFrame
public class CardLayoutDemo extends JFrame {
 
    // Initialization the value of
    // current card is 1 .
    private int currentCard = 1;
 
    // Declaration of objects
    // of CardLayout class.
    private CardLayout cl;
 
    public CardLayoutDemo()
    {
 
        // Function to set visibility of JFrame
        setTitle("Card Layout Example");
 
        // Function to set visibility of JFrame
        setSize(300, 150);
 
        // Creating Object of "Jpanel" class
        JPanel cardPanel = new JPanel();
 
        // Initialization of object "c1"
        // of CardLayout class.
        cl = new CardLayout();
 
        // set the layout
        cardPanel.setLayout(cl);
 
        // Initialization of object
        // "jp1" of JPanel class.
        JPanel jp1 = new JPanel();
 
        // Initialization of object
        // "jp2" of CardLayout class.
        JPanel jp2 = new JPanel();
 
        // Initialization of object
        // "jp3" of CardLayout class.
        JPanel jp3 = new JPanel();
 
        // Initialization of object
        // "jp4" of CardLayout class.
        JPanel jp4 = new JPanel();
 
        // Initialization of object
        // "jl1" of JLabel class.
        JLabel jl1 = new JLabel("Card1");
 
        // Initialization of object
        // "jl2" of JLabel class.
        JLabel jl2 = new JLabel("Card2");
 
        // Initialization of object
        // "jl3" of JLabel class.
        JLabel jl3 = new JLabel("Card3");
 
        // Initialization of object
        // "jl4" of JLabel class.
        JLabel jl4 = new JLabel("Card4");
 
        // Adding JPanel "jp1" on JFrame.
        jp1.add(jl1);
 
        // Adding JPanel "jp2" on JFrame.
        jp2.add(jl2);
 
        // Adding JPanel "jp3" on JFrame.
        jp3.add(jl3);
 
        // Adding JPanel "jp4" on JFrame.
        jp4.add(jl4);
 
        // Adding the cardPanel on "jp1"
        cardPanel.add(jp1, "1");
 
        // Adding the cardPanel on "jp2"
        cardPanel.add(jp2, "2");
 
        // Adding the cardPanel on "jp3"
        cardPanel.add(jp3, "3");
 
        // Adding the cardPanel on "jp4"
        cardPanel.add(jp4, "4");
 
        // Creating Object of "JPanel" class
        JPanel buttonPanel = new JPanel();
 
        // Initialization of object
        // "firstbtn" of JButton class.
        JButton firstBtn = new JButton("First");
 
        // Initialization of object
        // "nextbtn" of JButton class.
        JButton nextBtn = new JButton("Next");
 
        // Initialization of object
        // "previousbtn" of JButton class.
        JButton previousBtn = new JButton("Previous");
 
        // Initialization of object
        // "lastbtn" of JButton class.
        JButton lastBtn = new JButton("Last");
 
        // Adding JButton "firstbtn" on JFrame.
        buttonPanel.add(firstBtn);
 
        // Adding JButton "nextbtn" on JFrame.
        buttonPanel.add(nextBtn);
 
        // Adding JButton "previousbtn" on JFrame.
        buttonPanel.add(previousBtn);
 
        // Adding JButton "lastbtn" on JFrame.
        buttonPanel.add(lastBtn);
 
        // add firstbtn in ActionListener
        firstBtn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                 
                // used first c1 CardLayout
                cl.first(cardPanel);
 
                // value of currentcard is 1
                currentCard = 1;
            }
        });
 
        // add lastbtn in ActionListener
        lastBtn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
 
                // used last c1 CardLayout
                cl.last(cardPanel);
 
                // value of currentcard is 4
                currentCard = 4;
            }
        });
 
        // add nextbtn in ActionListener
        nextBtn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
 
                // if condition apply
                if (currentCard < 4)
                {
                     
                    // increment the value of currentcard by 1
                    currentCard += 1;
 
                    // show the value of currentcard
                    cl.show(cardPanel, "" + (currentCard));
                }
            }
        });
 
        // add previousbtn in ActionListener
        previousBtn.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent arg0)
            {
                // if condition apply
                if (currentCard > 1) {
 
                    // decrement the value
                    // of currentcard by 1
                    currentCard -= 1;
 
                    // show the value of currentcard
                    cl.show(cardPanel, "" + (currentCard));
                }
            }
        });
 
        // used to get content pane
        getContentPane().add(cardPanel, BorderLayout.NORTH);
 
        // used to get content pane
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);
    }
 
    // Main Method
    public static void main(String[] args)
    {
 
        // Creating Object of CardLayoutDemo class.
        CardLayoutDemo cl = new CardLayoutDemo();
 
        // Function to set default operation of JFrame.
        cl.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
 
        // Function to set visibility of JFrame.
        cl.setVisible(true);
    }
}


Output: 

Note: The above programs might not run in an online IDE. Please use an offline compiler.

Reference: https://docs.oracle.com/javase/7/docs/api/java/awt/CardLayout.html 
 



Previous Article
Next Article

Similar Reads

Java.awt.image.RescaleOp Class in Java with Examples
RescaleOp is a class in java.awt.image package which implements BufferedImageOp and RasterOp interface. This class performs a pixel-by-pixel rescaling of the data in the source image by multiplying the sample values for each pixel by a scale factor and then adding an offset. The scaled sample values are clipped to the minimum/maximum representation
5 min read
Java AWT vs Java Swing vs Java FX
Java's UI frameworks include Java AWT, Java Swing, and JavaFX. This plays a very important role in creating the user experience of Java applications. These frameworks provide a range of tools and components for creating graphical user interfaces (GUIs) that are not only functional but also visually appealing. As a Java developer, selecting the righ
11 min read
Java AWT | GridLayout Class
GridLayout class represents a layout manager with a specified number of rows and columns in a rectangular grid. The GridLayout container is divided into an equal-sized of rectangles, and one of the components is placed in each rectangle. Every rectangle cell has the same size therefore, they contain a component, which fills the entire cell. When th
5 min read
Java AWT | Cursor class with examples
Cursor class is a part of Java AWT package and it is used to create custom cursors or inherit system or predefined cursors. Cursor class is mainly used to encapsulate the bitmap representation of the mouse cursor. Constructor of cursor class are : Cursor(int t) : Creates a cursor with specified class Cursor(String name) : Creates a custom cursor wi
4 min read
Java AWT | Choice Class
Choice class is part of Java Abstract Window Toolkit(AWT). The Choice class presents a pop- up menu for the user, the user may select an item from the popup menu. The selected item appears on the top. The Choice class inherits the Component. Constructor for the Choice class Choice() : creates an new empty choice menu . Different Methods for the Cho
5 min read
Java AWT | Desktop Class
The Desktop class is a part of Java AWT package. This class is used to launch associated applications registered on the native desktop to handle a URI or a file. Important Points About Desktop Class : It can open a default web browser showing a specific URI It can launch default mail client with optional mailto URI It can launch a registered applic
5 min read
Java AWT | Color Class
The Color class is a part of Java Abstract Window Toolkit(AWT) package. The Color class creates color by using the given RGBA values where RGBA stands for RED, GREEN, BLUE, ALPHA or using HSB value where HSB stands for HUE, SATURATION, BRIcomponents. The value for individual components RGBA ranges from 0 to 255 or 0.0 to 0.1. The value of alpha det
9 min read
Java AWT | Dimension Class
Dimension class is a part of Java AWT. It contains the height and width of a component in an integer as well as double precision. The use of Dimension class is that many functions of Java AWT and Swing return dimension object. Constructors of the Dimension class Dimension() : It will create a new Object with height and width set to zero.Dimension(D
4 min read
Java AWT | Canvas Class
Canvas class is a part of Java AWT. Canvas is a blank rectangular area where the user can draw or trap input from the user. Canvas class inherits the Component class.Constructor of the Canvas class are : Canvas(): Creates a new blank canvas.Canvas(GraphicsConfiguration c): Creates a new canvas with a specified graphics configuration. Commonly used
3 min read
Java AWT | BorderLayout Class
BorderLayout is the default layout for the window objects such as JFrame, JWindow, JDialog, JInternalFrame etc. BorderLayout arranges the components in the five regions. Four sides are referred to as north, south, east, and west. The middle part is called the center. Each region can contain only one component and is identified by a corresponding co
4 min read
Article Tags :
Practice Tags :