Search code examples
javaswingcardlayout

New to java, panels not switched in my cardlayout


Can someone tell me what I am doing wrong please?

I have..

    JComboBox comboBox = new JComboBox();

    comboBox.addItem("Factor 1");
    comboBox.addItem("Factor 2");
    comboBox.addItem("Factor 3");

    comboBox.setSelectedIndex(-1);

    studyPlanController.setFactors(comboBox);
    MyItemListener itemListener = new MyItemListener();

    comboBox.addItemListener(itemListener);
    itemListener.setFactors(cardFactors);

and..

import java.awt.CardLayout;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

import javax.swing.JPanel;

public class MyItemListener implements ItemListener {
    JPanel factors;

    public void setFactors(JPanel factors) {
        this.factors = factors;
    }

    @Override
    public void itemStateChanged(ItemEvent e) {
        CardLayout cl = (CardLayout) (factors.getLayout());
        cl.show(factors, (String) e.getItem());
    }

}

When a breakpoint is placed in itemStateChanged(), and the combox is changed, then the breakpoint is hit, however the cardlayout remains uneffected.


Solution

  • Please take a look at http://docs.oracle.com/javase/tutorial/uiswing/layout/card.html

    Please check that you are adding the panels to card layout with same name as that shows up in the combobox. There might be mismatch in the names.