All About CardLayout in Java

0
84
Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share


This is unique from other layout managers in the sense that it represents several different layouts as living on separate index cards that can be shuffled so that any one card is on top at a given point of time. That means only one card is visible at a time,allowing applications to flip through the cards.This is useful for user interface that have optional components which can be dynamically enabled or disabled upon user input.
The structure of the class CardLayout is given as:


public class java.awt.CardLayout extends java.lang.Object implements java.awt.LayoutManager{
//constructors
public CardLayout();//default constructor ,creates a new card layout
public CardLayout(int hgap,int vgap);
//creates a new card layout with the specified horizontal and vertical gaps. The specified
//space between the components(gaps)The horizontal gaps are placed at the left and right edge.
//The vertical gaps are placed at the top and bottom edge.
//methods:
public void addLayoutComponent(String name,Component comp);
public void first(Container target);
public void last(Container target);
public void next(Container target);
public void previous(Container target);
public void layoutContainer(Container target);
public Dimension minimumLayoutSize(Container target);
public Dimension preferredLayoutSize(Container target);
public void removeLayoutSize(Container target);
public void show(Container target,String name);
public String toString();
}
An Example

Frame frame=new Frame();
CardLayout layout=new CardLayout();
frame.setLayout(layout);
frame.add("1",new Button("Card1"));
frame.add("2",new Button("Card2"));
frame.add("3",new Button("Card3"));
frame.add("4",new Button("Card4"));
public boolean keyDown(Event e,int key){
layout next(this);
return true;
}

add() method needs labels to pass a card name.We can refer the cards by card name. Here layout object is created first and then refer the same to frame.This is because we need to refer the CardLayout object after we have created it.

Don't miss out!
Subscribe To Newsletter

Receive top technical news, lesson ideas, travel tips and more!

Invalid email address
Give it a try. You can unsubscribe at any time.

Spread the love
  • 1
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
    1
    Share

LEAVE A REPLY

Please enter your comment!
Please enter your name here