So I just started practicing CardLayout
, but I can't seem to get it to work. I look at over 10 sites, and I seem to be doing the same thing as them, but for some reason my version isn't working. The next()
method is working fine, but calling show()
doesn't do anything.
private static CardLayout cards;
private static JPanel panel;
private Main() {
super("Card Layout");
setBounds(0, 0, 500, 500);
setDefaultCloseOperation(3);
panel = new JPanel();
add(panel);
cards = new CardLayout();
JPanel p1 = new JPanel();
p1.setBackground(Color.WHITE);
JPanel p2 = new JPanel();
p2.setBackground(Color.BLACK);
JPanel p3 = new JPanel();
p3.setBackground(Color.RED);
JPanel p4 = new JPanel();
p4.setBackground(Color.BLUE);
panel.add("white", p1);
panel.add("black", p2);
panel.add("red", p3);
panel.add("blue", p4);
panel.setLayout(cards);
// cards.next(panel); This works fine for me.
cards.show(panel, "red");
setVisible(true);
}
public static void main(String[] args) {
new Main();
}