Share on Google+Share on Google+

Java Swing Card Layout

This section illustrates you the use of Card layout in java swing.

Java Swing Card Layout

Java technology uses Layout Managers to define the location and size of Graphical User Interface components. It provides different types of Layout Managers which implements the LayoutManager interface. These are:

  • FlowLayout
  • GridLayout
  • BorderLayout
  • GridBagLayout
  • CardLayout
  • SpringLayout

Here we are going to discuss CardLayout. It is a space saving layout manager. Multiple components on card can be added but at a time only one card can be seen.

Here is the code:

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

public class CardLayoutExample extends JFrame {

	private int currentCard = 1;
	private JPanel cardPanel;
	private CardLayout cl;

	public CardLayoutExample() {

		setTitle("Card Layout Example");
		setSize(300, 150);
		cardPanel = new JPanel();

		cl = new CardLayout();
		JPanel p1 = new JPanel();
		JPanel p2 = new JPanel();
		JPanel p3 = new JPanel();
		JPanel p4 = new JPanel();
		JLabel lab1 = new JLabel("Card1");
		JLabel lab2 = new JLabel("Card2");
		JLabel lab3 = new JLabel("Card3");
		JLabel lab4 = new JLabel("Card4");

		cardPanel.add(p1, "1");
		cardPanel.add(p2, "2");
		cardPanel.add(p3, "3");
		cardPanel.add(p4, "4");
		JPanel buttonPanel = new JPanel();
		JButton b1 = new JButton("Previous");
		JButton b2 = new JButton("Next");
		b1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (currentCard > 1) {
					currentCard -= 1;, "" + (currentCard));

		b2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent arg0) {
				if (currentCard < 4) {
					currentCard += 1;, "" + (currentCard));
		getContentPane().add(cardPanel, BorderLayout.NORTH);
		getContentPane().add(buttonPanel, BorderLayout.SOUTH);

	public static void main(String[] args) {
		CardLayoutExample cl = new CardLayoutExample();



Posted on: August 19, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.