CardLayout
CardLayout is used to change the content of an application without opening a new Frame. For example, Login panel can be changed to Logout panel once user gets logged in.
Steps to apply CardLayout
1) Create a Panel(named: cardPanel) and set its layout to CardLayout.
2) Add another Panels(named: firstP, secondP, thirdP) to cardPanel as a Card. Give unique name to each panel.
3) Call CardLayout.show(cardPanel, “name of card”); to make desired card visible.
Program:
import java.awt.*;
import java.applet.Applet;
import java.awt.event.*;
public class CardLayoutDemo extends Applet implements ActionListener
{
Panel cardPanel;
Panel firstP, secondP, thirdP;
Panel buttonP;
Button first, second, third;
CardLayout ourLayout;
public void init()
{
cardPanel = new Panel();
ourLayout = new CardLayout();
cardPanel.setLayout (ourLayout);
firstP = new Panel();
firstP.setBackground(Color.blue);
secondP = new Panel();
secondP.setBackground(Color.yellow);
thirdP = new Panel();
thirdP.setBackground(Color.green);
first = new Button("First");
first.addActionListener(this);
second = new Button("Second");
second.addActionListener(this);
third = new Button("Third");
third.addActionListener(this);
buttonP = new Panel(); // Panel's default Layout manager is FlowLayout
buttonP.add(first);
buttonP.add(second);
buttonP.add(third);
this.setLayout(new BorderLayout());
this.add(buttonP, BorderLayout.SOUTH);
this.add(cardPanel, BorderLayout.CENTER);
cardPanel.add(firstP, "First"); //blue
cardPanel.add(secondP, "Second"); //yellow
cardPanel.add(thirdP, "Third"); //green
}
public void actionPerformed(ActionEvent e)
{
if (e.getSource() == first)
ourLayout.show(cardPanel, "First");
if (e.getSource() == second)
ourLayout.show(cardPanel, "Second");
if (e.getSource() == third)
ourLayout.show(cardPanel, "Third");
}
}
/*
<applet code="CardLayoutDemo" width="500" height="500"></applet>
*/
Output:




Recent Comments