CardLayout in java

CardLayout

  • It allows several different layout to be used
  • A CardLayout object is treats each component as a card.
  • Only one card visible at a time.
  • A panel has to be created to hold the deck as well as a panel for each card must be created
  • Component are then added to each card
Example

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.*;
public class test extends JFrame implements ActionListener
{
Container c;
CardLayout obj;
test()
{
c= getContentPane();
obj = new CardLayout(50,10);
c.setLayout(obj);
JButton b1=new JButton(“White”);
JButton b2=new JButton(“Orange”);
JButton b3=new JButton(“Green”);
JButton b4=new JButton(“Red”);
JButton b5=new JButton(“Blue”);
c.add(“First card”,b1);
c.add(“Second card”,b2);
c.add(“Third card”,b3);
c.add(“Fourth card”,b4);
c.add(“Fifth card”,b5);
b1.addActionListener((ActionListener) this);
b2.addActionListener(this);
b3.addActionListener(this);
b4.addActionListener(this);
b5.addActionListener(this);
}
public void actionPerformed(ActionEvent ae)
{
obj.next(c);
}
public static void main(String[] args)
{
test t = new test();
t.setSize(400,400);
t.setTitle(“Card Layout”);
t.setVisible(true);
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Output:

Untitled

 

 

After clicked on orange card, the next card with green will be displayed,

Untitled

 

Leave a Reply

Your email address will not be published. Required fields are marked *