Java AWT CardLayout Manager


After learning the basic layout managers (Flow, Border and Grid), let us study the advanced layout managers – CardLayout and GridBagLayout. These two managers are used in specific cases, but not often, where basic layout managers with panel combinations fail to fulfill the layout requirements.

Layout management is the procedure of deciding the size and the location of the component. We know earlier, each container, by default, is influenced by a layout manager (for example, BorderLayout for Frame), of course, which can be changed. A layout manager object carries out the layout management for the components existing in the container and is the final authority to decide the size and the position of the component.

When a component is added to a container, generally, it is added relative to the previous component, just one after another. It is the style of FlowLayout and GridLayout managers. But some layout managers demand to specify the position as in BorderLayout. To specify the location, the add() method is overloaded in BorderLayout that takes an additional string parameter like North or South etc.

CardLayout is used to display one card at a time among multiple cards. This manager considers each component placed in the container as a card. Container treats all the components as a stack of cards and only one card is seen at a time.

CardLayout manager’s usage is very need-based and quiet different from others where other layout managers try to display all the components added to the container. But card layout manager displays only one component at a time. Where a tabbed panel, like Page Setup option in MS Word, is required we use card layout manager. Another example is MS Excel workbook in which the selected sheet is opened by clicking over sheet tab.

CardLayout Basics

Each component added to the container, using CardLayout, is treated as a card. Multiple components added comprises of multiple cards (each component becomes a card). Even though multiple cards exist, only one card can be seen at a time. This type of arrangement saves a lot of space.

class CardLayout

The CardLayout manager is represented by CardLayout class from java.awt package.

Following is the class signature

public class CardLayout extends Object implements LayoutManager2, Serializable

Following are the constructors

  1. CardLayout(): Creates a CardLayout object with zero pixels horizontal and vertical gaps.
  2. CardLayout(int hgap, int vgap): Creates a CardLayout object with the specified horizontal gap of hgap and vertical gap of vgap.

This layout provides many methods to navigate all through the cards. Following are some important methods.

  1. void first(Container parent): Displays the first component placed with the card layout.
  2. void last(Container parent): Displays the last component placed with the card layout.
  3. void next(Container parent): Displays the next component to the current one.
  4. void previous(Container parent): Displays the previous component to the current one.
  5. void show(Container parent, String ref): Displays the exact component needed.
  6. int getHgap(): Returns the horizontal gap existing with CardLayout object.
  7. int getVgap(): Returns the vertical gap existing with CardLayout object.
  8. void setHgap(int hgap): Sets horizontal gap with the specified hgap. This method is used to set the gap when the default constructor is used to create the CardLayout object.
  9. void setVgap(int vgap): Sets vertical gap with the specified vgap. This method is used to set the gap when the default constructor is used to create the CardLayout object.

The cards can be navigated using the above methods. If you are lost in the cards, the first() method takes you to the first card and last() method takes to the last card. The following program illustrates.

First Program: Hyderabad Traveler – I

The following example is developed by keeping in view of a traveler who visits Hyderabad (India). He is furnished with the places of visit in Hyderabad like Gardens and Monuments etc. For this, CardLayout is used.

import java.awt.*;   
import java.awt.event.*; 
public class TwinCities extends Frame implements ActionListener  
{   
  List tl, gl, ml, al;              // 4 lists to add to a container that implements card layout
  Button fb, lb, nb, pb;       	    // 4 buttons to navigate the cards of the container
  CardLayout cl;  
  Panel sp, bp;                	    // 2 panels to add lists and buttons
  public TwinCities()  
  {
    super("Welcome to Hyderabad -- now Cyberabad");                // title to Frame
    tl = new List(4);                // instantiate list objects 
    gl = new List(4);
    ml = new List(4);   
    al = new List(4);
  				    // populate theaters list
    tl.add("Sudersan complex");                            
    tl.add("Sandhya complex");   
    tl.add("Odeon complex");
    tl.add("Ramakrishana Estate");    
    tl.add("IMAX 70MM");
    tl.add("Surya 35MM");
    tl.add("Shanthi 70MM");
          			    // populate gardens list 
    gl.add("Indira Park");    
    gl.add("Lumbibi Park");  
    gl.add("Sanjivayya Park");
    gl.add("Zoo Park");
    gl.add("Public Gardens");
				    // populate monuments list
    ml.add("Chiran Palace");  	
    ml.add("Falaknuma Palace");
    ml.add("Charminar");
    ml.add("QQ Tombs"); 
    ml.add("Golconda Fort");  
    ml.add("Zuma Majid");
			  	    // populate special attractions list
    al.add("Birla Mandir");          
    al.add("Planetorium");
    al.add("Hi-Tech city");  
    al.add("Buddha Purnima");
    al.add("Ramoji Filmcity");
    al.add("Shilparamam");

    cl = new CardLayout();          // create a card layout object
    sp = new Panel();  		    // create a panel to add all the lists
    sp.setLayout(cl);               // set the layout to panel, sp

    sp.add(tl, "t");    	    // add lists to panel
    sp.add(gl, "g");                                   
    sp.add(ml, "m");                // the string parameter is for show() later
    sp.add(al, "a");
			             // instantiate buttons
    fb = new Button("First Button");    
    lb = new Button("Last Button");
    nb = new Button("Next Button");   
    pb = new Button("Previous Button");

    bp = new Panel() ;     		// create a panel to add buttons
    bp.setLayout(new GridLayout(1, 4));  // set lay out to bp panel
    bp.add(fb);                          // add each button to panel
    bp.add(nb);  
    bp.add(pb);  
    bp.add(lb);
						
    fb.addActionListener(this);          // register the buttons with listener
    nb.addActionListener(this);
    pb.addActionListener(this); 
    lb.addActionListener(this);

    add(bp, "South");                    // add panels to frame
    add(sp, "Center");    		                 

    setSize(300, 300);  
    setVisible(true) ;
  }
  public void actionPerformed(ActionEvent e)  
  {
    String str = e.getActionCommand();
    if(str.equals("First Button"))
        cl.first(sp) ;                                         
    else if(str.equals("Next Button"))
	cl.next(sp);
    else if(str.equals("Previous Button"))
	cl.previous(sp);
    else if(str.equals("Last Button"))
	cl.last(sp);
  }
  public static void main(String args[])   
  {   
    new TwinCities();  
  }
}

Output screen of TwinCities.java

Four List component objects, tl, gl, ml, al are created to represent 4 cards that display theaters, gardens, monuments and special attractions of Hyderabad city (India). Also four buttons, fb, lb, nb, pb are created to navigate the 4 cards. Here, each list represents a card. A special panel, sp and a button panel, bp are created to add the lists and buttons. One CardLayout object cl is created to set to the panel, sp.

super(“Welcome to Hyderabad — now Cyberabad”);

This is another style of giving a title to the frame. It is equivalent to setTitle() method. super() method should be used as the first statement in the constructor. super() with a string parameter, calls the super class matching constructor (of Frame) and passes the string. This displays the title to the frame.

All the lists are populated with add() method. The special panel sp is set to CardLayout. That is, now the sp panel is under the influence of CardLayout. All the 4 lists are added to sp.

sp.add(tl, “t”);

The list tl is added to the special panel along with a string “t“. This string t is not used in this program but used in the next program. This string t is used as an identifier to identify the list tl.

The 4 buttons are added to button panel, bp. Panel bp is set with GridLayout.

String str = e.getActionCommand();
if(str.equals(“First Button”))
cl.first(sp) ;

The string object str represents the button label clicked. When the str is “First Button”, the first() method of CardLayout is called and the special panel displays the first list added to it. Similarly with next() and previous() etc. methods.

sp panel containing lists is added at the center of the frame. List does not display the scrollbar. This is a good example to show where layout managers will have the supremacy in designing the component (here, List). Even though list is set for 4 items and the number of items added is more, still scroll bar is not supplied by JVM. This is for the reason that sufficient space is available for the list to display all the items. Obviously, scrollbar is not necessary when all the items of the list are displayed.

If the number of lists are many, the traveler finds trouble, to get the appropriate list displayed with such type of navigation where it requires a lot of clicks and looses the patience. If the buttons are labeled like Parks and Monuments etc., the user can click the exact button and get displayed the wanted card (or list). The above program is modified for this effect. Here, we make use of the left over (unused in the previous program) method of card layout, the show() method.

Second Program: Hyderabad Traveler – II

The following program is a modified version of previous program where show() method of CardLayout is used. The extra statements added in this program are bold faced for easy identification.

import java.awt.*;   
import java.awt.event.*; 
public class Hyderabad_Secunderabad extends Frame implements ActionListener  
{   
  List tl, gl, ml, al;     
  Button fb, lb, nb, pb;   
  CardLayout cl;  
  Panel sp, bp;                                                                
  Panel ep;                               // extra panel to add new buttons created in this program
  Button tb, gb, mb, sb;                  // extra buttons

  public Hyderabad_Secunderabad()  
  {
    super("Welcome to Hyderabad, India"); // title to the Frame
    tl = new List(4);                                
    gl = new List(4);
    ml = new List(4);   
    al = new List(4);

    tl.add("Sudersan complex");                            
    tl.add("Sandhya complex");   
    tl.add("Odeon complex");
    tl.add("Ramakrishana Estate");    
    tl.add("IMAX 70MM");
    tl.add("Surya 35MM");
    tl.add("Shanthi 70MM");

    gl.add("Indira Park");                       
    gl.add("Lumbibi Park");  
    gl.add("Sanjivayya Park");
    gl.add("Zoo Park");
    gl.add("Public Gardens");

    ml.add("Chiran Palace");  
    ml.add("Falaknuma Palace");
    ml.add("Charminar");
    ml.add("QQ Tombs"); 
    ml.add("Golconda Fort");  
    ml.add("Zuma Majid");

    al.add("Birla Mandir");    
    al.add("Planetorium");
    al.add("Hi-Tech city");  
    al.add("Buddha Purnima");
    al.add("Ramoji Filmcity");
    al.add("Shilparamam");

    cl = new CardLayout();                        
    sp = new Panel();                                                    
    sp.setLayout(cl);                                                     
        
    sp.add(tl,"t");
    sp.add(gl,”g");                                      
    sp.add(ml,”m") ; 
    sp.add(al,”a") ;                 
    fb = new Button("First Button");    
    lb = new Button("Last Button");
    nb = new Button("Next Button");  
    pb = new Button("Previous Button");

    bp = new Panel() ;     				         
    bp.setLayout(new GridLayout(1, 4)) ;                        
    bp.add(fb);   
    bp.add(nb);  
    bp.add(pb);  
    bp.add(lb);
                                                 
    ep = new Panel();      		// create extra panel
    ep.setLayout(new GridLayout(1, 4, 5, 0)); // grid layout with gaps
    tb = new Button("Theatres");       
    gb = new Button ("Gardens");
    mb = new Button("Monuments"); 
    sb = new Button("Special");
    ep.add(tb);  
    ep.add(gb);  
    ep.add(mb);  
    ep.add(sb);

    fb.addActionListener(this);  
    nb.addActionListener(this);
    pb.addActionListener(this); 
    lb.addActionListener(this);
    tb.addActionListener(this);  
    gb.addActionListener(this);
    mb.addActionListener(this);  
    sb.addActionListener(this);

    add(bp, "South");  
    add(sp, "Center") ;      
    add(ep, "North") ;

    setSize(300, 300);  
    setVisible(true) ;
  }
  public void actionPerformed(ActionEvent e)  
  {
    String str = e.getActionCommand() ;
    if(str.equals("First Button"))
	cl.first(sp) ;                                          
    else if(str.equals("Next Button"))
	cl.next(sp);
    else if(str.equals("Previous Button"))
	cl.previous(sp);
    else if(str.equals("Last Button"))
	cl.last(sp);
    else if(str.equals("Theatres"))
	cl.show(sp, "t");
    else if(str.equals("Gardens"))
	cl.show(sp, "g");
    else if(str.equals("Monuments"))
	cl.show(sp, "m");
    else if(str.equals("Special"))
	cl.show(sp, "a");
  }
  public static void main(String args[])   
  {   
    new Hyderabad_Secunderabad();  
  }
}
Output screen of Hyderabad_Secunderabad.java

To add 4 more new buttons, tb, gb, mb and sb, an extra panel ep is created. The ep panel is set with GridLayout. The 4 buttons are instantiated and added to the panel. As usual listener is also registered.

else if(str.equals(“Theatres”))
cl.show(sp, “t”);

If Theatres button is clicked, the show() method of CardLayout is called. This method displays the card identified by the string t existing in the panel sp. This is nothing but the Theaters list. This is the advantage of the show() method which opens the exact of card when a buttons is clicked. This is the easiest and time saving navigation among cards.

Leave a Comment

Your email address will not be published.