Java examples for Swing:CardLayout
Create a Wizard with CardLayout
import java.awt.CardLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.ButtonGroup; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JRadioButton; public class Main extends JFrame { public Main() { super("Survey"); setSize(290, 140);//from w w w .j av a 2 s . com setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); SurveyWizard wiz = new SurveyWizard(); add(wiz); setVisible(true); } public static void main(String[] arguments) { Main surv = new Main(); } } class SurveyWizard extends JPanel implements ActionListener { int currentCard = 0; CardLayout cards = new CardLayout(); QuestionPanel[] ask = new QuestionPanel[3]; public SurveyWizard() { super(); setSize(240, 140); setLayout(cards); // set up survey String question1 = "What is your gender?"; String[] responses1 = { "female", "male"}; ask[0] = new QuestionPanel(question1, responses1, 2); String question2 = "What is your age?"; String[] responses2 = { "Under 25", "25-34", "35-54", "Over 54" }; ask[1] = new QuestionPanel(question2, responses2, 1); String question3 = "How often do you exercise each week?"; String[] responses3 = { "Never", "1-3 times", "More than 3" }; ask[2] = new QuestionPanel(question3, responses3, 1); ask[2].setFinalQuestion(true); addListeners(); } private void addListeners() { for (int i = 0; i < ask.length; i++) { ask[i].nextButton.addActionListener(this); ask[i].finalButton.addActionListener(this); add(ask[i], "Card " + i); } } public void actionPerformed(ActionEvent evt) { currentCard++; if (currentCard >= ask.length) { System.exit(0); } cards.show(this, "Card " + currentCard); } } class QuestionPanel extends JPanel { JLabel question; JRadioButton[] response; JButton nextButton = new JButton("Next"); JButton finalButton = new JButton("Finish"); QuestionPanel(String ques, String[] resp, int def) { super(); setSize(160, 110); question = new JLabel(ques); response = new JRadioButton[resp.length]; JPanel sub1 = new JPanel(); ButtonGroup group = new ButtonGroup(); JLabel quesLabel = new JLabel(ques); sub1.add(quesLabel); JPanel sub2 = new JPanel(); for (int i = 0; i < resp.length; i++) { if (def == i) { response[i] = new JRadioButton(resp[i], true); } else { response[i] = new JRadioButton(resp[i], false); } group.add(response[i]); sub2.add(response[i]); } JPanel sub3 = new JPanel(); nextButton.setEnabled(true); sub3.add(nextButton); finalButton.setEnabled(false); sub3.add(finalButton); GridLayout grid = new GridLayout(3, 1); setLayout(grid); add(sub1); add(sub2); add(sub3); } void setFinalQuestion(boolean finalQuestion) { if (finalQuestion) { nextButton.setEnabled(false); finalButton.setEnabled(true); } } }