Java AWT CardLayout class

Introduction

The CardLayout class manages components by layers.

CardLayout provides these two constructors:

CardLayout()  
CardLayout(int horz, int vert) 

When card panels are added to a panel, they are usually given a name.

void add(Component panelRef, Object name) 

The following example creates a two-level card deck.

import java.awt.CardLayout;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JFrame;
import javax.swing.JPanel;

class Demo extends JPanel implements ActionListener, MouseListener {
  JCheckBox windowsXP, windows7, windows8, android, solaris, mac;
  JPanel osCards;//from w  w w. ja v a2  s .c o  m
  CardLayout cardLO;
  JButton Win, Other;

  public Demo() {
    Win = new JButton("Windows");
    Other = new JButton("Other");
    add(Win);
    add(Other);

    cardLO = new CardLayout();
    osCards = new JPanel();
    osCards.setLayout(cardLO); // set panel layout to card layout

    windowsXP = new JCheckBox("Windows XP", null, true);
    windows7 = new JCheckBox("Windows 7", null, false);
    windows8 = new JCheckBox("Windows 8", null, false);
    android = new JCheckBox("Android");
    solaris = new JCheckBox("Solaris");
    mac = new JCheckBox("Mac OS");

    // add Windows check boxes to a panel
    JPanel winPan = new JPanel();
    winPan.add(windowsXP);
    winPan.add(windows7);
    winPan.add(windows8);

    // Add other OS check boxes to a panel
    JPanel otherPan = new JPanel();
    otherPan.add(android);
    otherPan.add(solaris);
    otherPan.add(mac);

    // add panels to card deck panel
    osCards.add(winPan, "Windows");
    osCards.add(otherPan, "Other");

    add(osCards);

    Win.addActionListener(this);
    Other.addActionListener(this);

    addMouseListener(this);
  }

  public void mousePressed(MouseEvent me) {
    cardLO.next(osCards);
  }

  public void mouseClicked(MouseEvent me) {
  }

  public void mouseEntered(MouseEvent me) {
  }

  public void mouseExited(MouseEvent me) {
  }

  public void mouseReleased(MouseEvent me) {
  }

  public void actionPerformed(ActionEvent ae) {
    if (ae.getSource() == Win) {
      cardLO.show(osCards, "Windows");
    } else {
      cardLO.show(osCards, "Other");
    }
  }
}

public class Main {
  public static void main(String[] args) {
    Demo panel = new Demo();

    JFrame application = new JFrame();

    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    application.add(panel);
    application.setSize(250, 250);
    application.setVisible(true);
  }
}



PreviousNext

Related