Java CardLayout

Java CardLayout

The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout.

Constructors of CardLayout class

  1. CardLayout(): creates a card layout with zero horizontal and vertical gap.
  2. CardLayout(int hgap, int vgap): creates a card layout with the given horizontal and vertical gap.

Commonly used methods of CardLayout class

  • public void next(Container parent): is used to flip to the next card of the given container.
  • public void previous(Container parent): is used to flip to the previous card of the given container.
  • public void first(Container parent): is used to flip to the first card of the given container.
  • public void last(Container parent): is used to flip to the last card of the given container.
  • public void show(Container parent, String name): is used to flip to the specified card with the given name.

Example of CardLayout class

CardLayout class

  1. import java.awt.*;
  2. import java.awt.event.*;
  3. import javax.swing.*;
  4. public class CardLayoutExample extends JFrame implements ActionListener{
  5. CardLayout card;
  6. JButton b1,b2,b3;
  7. Container c;
  8.     CardLayoutExample(){
  9.         c=getContentPane();
  10.         card=new CardLayout(40,30);
  11. //create CardLayout object with 40 hor space and 30 ver space
  12.         c.setLayout(card);
  13.         b1=new JButton(“Apple”);
  14.         b2=new JButton(“Boy”);
  15.         b3=new JButton(“Cat”);
  16.         b1.addActionListener(this);
  17.         b2.addActionListener(this);
  18.         b3.addActionListener(this);
  19.         c.add(“a”,b1);c.add(“b”,b2);c.add(“c”,b3);
  20.     }
  21.     public void actionPerformed(ActionEvent e) {
  22.     card.next(c);
  23.     }
  24.     public static void main(String[] args) {
  25.         CardLayoutExample cl=new CardLayoutExample();
  26.         cl.setSize(400,400);
  27.         cl.setVisible(true);
  28.         cl.setDefaultCloseOperation(EXIT_ON_CLOSE);
  29.     }
  30. }
download this example

 

Next TopicJava GridBagLayout
java for beginners
java for beginners
java for beginners
CodSir //course // books
...

WikiSir

Java CardLayout The CardLayout class manages the components in such a manner that only one component is visible at a time. It treats each component as a card that is why it is known as CardLayout. Constructors of CardLayout class CardLayout(): creates a card layout with zero horizontal and vertical gap. CardLayout(int hgap, int vgap): creates a […]

Tags:

....
...