Jump to Real's How-to Main page

Use The CardLayout manager

import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class CardLayoutDemo extends Applet 
  implements ActionListener{ 
 Panel p1,p2,p3,p0;
 Choice c1,c2;
 Button b1,b2,b3, b4;
 TextField t1, t2;

 public void init() {
  // The first Card
  p1 = new myPanel(new Color(0).red,
              new FlowLayout(),
         100,100) ;
  Choice c1 = new Choice();
  c1.addItem("Option 1");
  c1.addItem("Option 2");
  p1.add(c1);

  // The second Card
  p2 = new myPanel(new Color(0).blue,
         new FlowLayout(),
              100, 100);
  c2 = new Choice();
  c2.addItem("Option A");
  c2.addItem("Option B");
  c2.addItem("Option C");
  p2.add(c2);

  // the third Card
  p3 = new myPanel(new Color(0).black,
         new FlowLayout(),
         100, 100);
  t1 = new TextField(8);
  t1.setBackground(new Color(0).white);
  p3.add(t1);
                        
  // Main card (receive the other)
  p0 = new myPanel(new Color(0).white,
               new CardLayout(0,0),
          100,100);
  setLayout(new FlowLayout());
  add(p0);

  // Add cards
  p0.add("First card", p1);
  p0.add("2nd card", p2);
  p0.add("3rd card", p3);


  add(b1 = new Button("card 1"));
  add(b2 = new Button("card 2"));
  add(b3 = new Button("card 3"));
  add(b4 = new Button("Which card is selected ?"));
  add(t2 = new TextField(2));
  b1.addActionListener(this);
  b2.addActionListener(this);
  b3.addActionListener(this);
  b4.addActionListener(this); 
  }

 public void actionPerformed(ActionEvent e) {
  if (e.getSource() == b1) {
    //Show the first list
    ((CardLayout)p0.getLayout()).show(p0, "First card");
    }
  else if (e.getSource() == b2) {
    //Show the second list
    ((CardLayout)p0.getLayout()).show(p0, "2nd card");
    }
  else if (e.getSource() == b3) {
    //Show the third list
    ((CardLayout)p0.getLayout()).show(p0, "3rd card");  
    }
  else if (e.getSource() == b4) {
    // get the current card
    Component c[] = p0.getComponents();
    int i = 0;
    int j = c.length;
    while (i < j) {
       if (c[i].isVisible()) {
          t2.setText("" + (i+1));
          break;
          }
       else
          i ++;
       }
    }
  }
 }

class myPanel extends Panel{
 int w;
 int h;
        
 myPanel(Color co, LayoutManager la, int width, int height){
   super();
   w = width;
   h = height;
   setBackground(co);
   setLayout(la);
   }
                
 public Dimension getMinimumSize() {
   return new Dimension(w,h);
   }

 public Dimension getPreferredSize() {
   return new Dimension(w,h);
   }
}
<HTML>
  <TABLE><TR><TD>
  <APPLET CODE=CardLayoutDemo.class WIDTH=300 HEIGHT=300>
  </APPLET>
</HMTL>
Try it here.
If you find this article useful, consider making a small donation
to show your support for this Web site and its content.

Written and compiled by Réal Gagnon ©1998-2005
[ home ]