Tuesday, 11 March 2014

LAYOUT MANAGERS:CardLayout

A CardLayout object is a layout manager for a container. It treats each component in the container as a card.......

CardLayout


A CardLayout object is a layout manager for a container. It treats each component in the container as a card. Only one card is visible at a time, and the container acts as a stack of cards. The first component added to a CardLayout object is the visible component when the container is first displayed. The ordering of cards is determined by the container's own internal ordering of its component objects. CardLayout defines a set of methods that allow an application to flip through these cards sequentially, or to show a specified card. The addLayoutComponent(java.awt.Component, java.lang.Object) method can be used to associate a string identifier with a given card for fast random access.

CardLayout provides these two constructors


  • CardLayout():Creates a new card layout with gaps of size zero.
  • CardLayout(int hgap, int vgap):Creates a new card layout with the specified horizontal and vertical gaps.


CardLayout provides these Methods


  • void previous(Container parent):Selects the previous component.
  • void first(Container parent):Selects the first component.
  • void last(Container parent):Selects the last component.
  • void show(Container parent, String name):Selects the component associated with the String object name.


sample program to demonstrate CardLayout


import java.awt.CardLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JPanel;
public class TryCardLayout extends JPanel implements ActionListener
{
CardLayout card = new CardLayout(50, 50); // Create layout
public TryCardLayout() 
{
setLayout(card);
JButton button;
for (int i = 1; i <= 6; i++) 
{
 add(button = new JButton(" Press " + i), "Card" + i); // Add a button
 button.addActionListener(this); // Add listener for button
 }
}
 // Handle button events
public void actionPerformed(ActionEvent e) 
{
card.next(this); // Switch to the next card
}
 public static void main(String[] args) {
JFrame aWindow = new JFrame();
aWindow.setBounds(30, 30, 300, 300);
aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
aWindow.getContentPane().add(new TryCardLayout());
aWindow.setVisible(true);
}
}

output:


No comments :

Post a Comment