Card layout explained!!!

            Card layout treats the components like a speck of cards. In the way,the card which is on the top only is visible on the deck, the component on the top only is visible in this layout. Other components will be under the hood. We can flip any card to the top to make it visible. This is similar to JTabbedPane except that it has its own interface for each tab.

           Lets put it in an example. We create a JFrame with a JComboBox. Combo box contains two values(lets say textfields and buttons). When the value textfields is selected, we show up two JTextFields under the combo box. For buttons, we bring up two Buttons on the UI.

Lets try this out in code.

1.First lets create a class named CardLayoutDemo which extends JFrame.

public class CardLayoutDemo extends JFrame
{
      public CardLayoutDemo()
     {
           super(“CardLayoutDemo”); // setting title of the frame
      }
}

2. Create two final variables for holding string namely TEXTFIELDS and BUTTONS

private final String TEXTFIELDS = “textfields”;
private final String BUTTONS = “buttons”;

3. Create initGUI() method for initializing GUI components(my way of coding!!)

private void initGUI()
{
        // Make the frame dispose on close
         setDefaultCloseOperation(DISPOSE_ON_CLOSE);

        // Create a combo box containing the values and add it to a panel
       ComboBoxModel model = new DefaultComboBoxModel(new String[]{TEXTFIELDS,BUTTONS});
      JComboBox combo = new JComboBox(model);
      JPanel comboPanel = new JPanel();
      comboPanel.add(combo);

      // Add an ItemListener to combo box
     combo.addItemListener(new ItemListener()
     {
           @Override
           public void itemStateChanged(ItemEvent e)
          {
                CardLayout c = (CardLayout) cardPanel.getLayout();
                 c.show(cardPanel, (String) e.getItem());
          }
    });

    // panel containing textfields
     JPanel card1 = new JPanel(new GridBagLayout());
    JTextField field1 = new JTextField();
    JTextField field2 = new JTextField();
     card1.add(field1, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new                                     Insets (10, 10, 10, 10), 0, 0));
    card1.add(field2, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.BOTH, new   Insets(10, 10, 10, 10), 0, 0));
  // I have used GridBagLayout here as it is my favourite layout
  // Any other layouts can be used.

   // panel containing buttons
   JPanel card2 = new JPanel(new GridBagLayout());
   JButton button1 = new JButton(“Button1”);
   JButton button2 = new JButton(“Button2”);
   card2.add(button1, new GridBagConstraints(0, 0, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, new  Insets(10, 10, 10, 10), 0, 0));
   card2.add(button2, new GridBagConstraints(0, 1, 1, 1, 1, 1, GridBagConstraints.WEST, GridBagConstraints.NONE, new Insets(10, 10, 10, 10), 0, 0));
}

4. Declare a JPanel for holding the cards

            private JPanel cardPanel;

5. In initGUI() method, initialize the cardPanel and add all the panels to the frame

// create a panel for holding the cards
cardPanel = new JPanel(new CardLayout());
cardPanel.add(card1, TEXTFIELDS);
cardPanel.add(card2,BUTTONS);

Container c = getContentPane();
c.add(comboPanel,BorderLayout.PAGE_START);
c.add(cardPanel, BorderLayout.CENTER);
setContentPane(c);
pack();
// for keeping the frame at the center of the window
setLocationRelativeTo(null);
setVisible(true);

6. Now create the main method

public static void main(String[] args)
{
        // for thread safety this should be invoked in Event dispatcher thread
        SwingUtilities.invokeLater(new Runnable() {

        @Override

        public void run() {
             new CardLayoutDemo();
        }
      });
 }

Now you are good to go. Execute the program. You can see a Frame at the center of the screen with a combo box and textfields. Try changing the combobox value to buttons. Now you will be seeing buttons in the same area where text fields were present before. Magic!!! Isn’t it???