Search code examples
javaswingjpanelcardlayout

Why are the cards not appearing on JPanel CardLayout?


My application consists of two JPanels that will be cards on a MainPanel. The code is as below. For some reason, the panels don't appear. I'd be very grateful for your help :)

MainPanel.java:

public class MainPanel extends JPanel{

    private final static String PANEL1 = "PANEL1";
    private final static String PANEL2 = "PANEL2";

    private static Panel1 panel1;
    private static Panel2 panel2;

    //private static CardLayout layout;

    public MainPanel() {

        super(new CardLayout());

        panel1 = new Panel1();
        panel2 = new Panel2();

        getLayout().addLayoutComponent(PANEL1, panel1);
        getLayout().addLayoutComponent(PANEL2, panel2);


        ((CardLayout) getLayout()).show(this, PANEL1); 
    }

}

Main.java:

public class Main {

    private static JFrame window;

    public static void main(String[] args) {

        window = new JFrame();

        window.setContentPane(new MainPanel());
        window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        window.setSize(600,400);
        window.setVisible(true);
    }

}

Solution

  • This

    getLayout().addLayoutComponent(PANEL1, panel1);
    getLayout().addLayoutComponent(PANEL2, panel2);
    

    should be

    add(panel1, PANEL1);
    add(panel2, PANEL2);
    

    For more information, see How to Use CardLayout.