Card
Home Up Border Card Flow Grid Null

 

Card Layout

A card is like a Hypercard card on a MacIntosh or a flip-book style preference (such as what you see when you go to System Properties through the Control Panel) in a Windows environment.  There are two ways to invoke the card layout manager:

  1.   setLayout (new CardLayout());

    This invokes the standard card layout manager.  A series of "cards" is created and the card layout manager decides which one to display.
  2.   setLayout (new CardLayout(int, int));

    The two parameters indicate the horizontal gap in pixels from the card to other components and the vertical gap in pixels from the card to other components.

The card layout manager is more difficult to use than the other layout managers, due to the fact that the "cards" must appear in a container that is a subpart of the main display window.  Once cards have been added to a container managed by the CardLayout manager, there are four built-in methods that are useful:

  1. next(Container):  the next "card" located in the container is displayed.
  2. previous(Container): the previous "card" in the container is displayed.
  3. first(Container): the first "card" in the container is displayed.
  4. last(Container): the last "card" in the container is displayed.

Example

In the example below, the main window consists of both a panel and a button.   Clicking on the button causes the "next" card to be displayed in the panel.  (Would you like more information on event handling?)  The panel is a 100 by 100 container that uses the CardLayout manager.  There are three possible cards that can be displayed on the panel:  the redCanvas, the whiteCanvas, and the blueCanvas.  Each of these must be "added" to the panel.  Initially, the redCanvas is displayed.  Clicking on the "cycle" button causes the whiteCanvas to be displayed.  Clicking again causes the blueCanvas to be displayed, etc.  Run this code and conduct experiments with it until you understand how the CardLayout manager works.

import java.awt.*;
import java.applet.*;      
public class Card extends Applet
{
	public void init ()
	{
		Button b = new Button("cycle");   
                p = new Panel ();
                c = new CardLayout ();         
		p.resize(100, 100);
		p.setLayout(c);              
		MyCanvas redCanvas = new MyCanvas ( Color.red );
		MyCanvas whiteCanvas = new MyCanvas ( Color.white );
		MyCanvas blueCanvas = new MyCanvas ( Color.blue );              
		p.add (redCanvas);
		p.add (whiteCanvas);
		p.add (blueCanvas);              
		add (p);
		add (b);
	}              
	public boolean handleEvent (Event e)
	{
		if (e.target instanceof Button)
		{
			c.next(p);
			return true;
		}
		else
			return false;
	}              
	private Panel p;
	private CardLayout c;
}              
class MyCanvas extends Canvas
{
	public MyCanvas (Color c)
	{
		setBackground(c);
		resize(50,50);
	}
}            
What You'll See: