CardLayout Demo

This example shows the CardLayout manager. Pressing any one of three button available will show a different "card". Ex.If red Button is clicked,the panel with re background is Shown. Panels in card layout are switched using show() method.

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


public class CardLayoutDemo extends Frame implements ActionListener
{


Panel cardPanel;
Panel p1,p2,p3;
Panel buttonP;

Button b1,b2,b3;
CardLayout cLAyout;


public void cardLayoutDemo()
{

cardPanel=new Panel();
cLAyout=new CardLayout();
cardPanel.setLayout(cLAyout);

p1=new Panel();
p1.setBackground(Color.red);
p2=new Panel();
p2.setBackground(Color.black);
p3=new Panel();
p3.setBackground(Color.gray);

b1=new Button("Red");
b2=new Button("Black");
b3=new Button("Gray");

b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);

buttonP=new Panel();
buttonP.add(b1);
buttonP.add(b2);
buttonP.add(b3);

cardPanel.add(p1,"b1");
cardPanel.add(p2,"b2");
cardPanel.add(p3,"b3");

setLayout(new BorderLayout());
add(buttonP,BorderLayout.SOUTH);
add(cardPanel,BorderLayout.CENTER);
setVisible(true);
setSize(300,200);
setTitle("Demo Card");

addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
});

}

public void actionPerformed(ActionEvent e) {

if(e.getSource()==b1)
{
cLAyout.show(cardPanel, "b1");
}
if(e.getSource()==b2)
{
cLAyout.show(cardPanel, "b2");
}
if(e.getSource()==b3)
{
cLAyout.show(cardPanel, "b3");
}
}
public static void main(String args[])
{
CardLayoutDemo demo=new CardLayoutDemo();
demo.cardLayoutDemo();
}

}

Output will Show As Below :


No comments: