Java Swing Tutorial - Java CardLayout .addLayoutComponent (Component comp, Object constraints)








Syntax

CardLayout.addLayoutComponent(Component comp, Object constraints) has the following syntax.

public void addLayoutComponent(Component comp,   Object constraints)

Example

In the following code shows how to use CardLayout.addLayoutComponent(Component comp, Object constraints) method.

// ww  w . ja va 2s.c  o m
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 Main {

  public static void main(String[] args) {
    JFrame aWindow = new JFrame();
    aWindow.setSize(400, 400);
    aWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    aWindow.add(new CardLayoutPanel());
    aWindow.setVisible(true);
  }
}

class CardLayoutPanel extends JPanel implements ActionListener {
  CardLayout card = new CardLayout(50, 50);

  public CardLayoutPanel() {
    setLayout(card);
    JButton button = new JButton("Press 1");
    button.addActionListener(this);
    card.addLayoutComponent(button, "1");
    add(button);    
    
    button = new JButton("Press 2");
    button.addActionListener(this);
    card.addLayoutComponent(button, "2");
    add(button);
    
    button = new JButton("Press 3");
    button.addActionListener(this);
    card.addLayoutComponent(button, "3");
    add(button);

    card.show(this, "2");
  }
  public void actionPerformed(ActionEvent e) {
    card.next(this);
  }
}