CardLayout 的显示方法不执行任何操作

CardLayout's Show Method Not Doing Anything

所以我刚开始练习 CardLayout,但我似乎无法让它发挥作用。我查看了 10 多个站点,我似乎在做与他们相同的事情,但出于某种原因,我的版本无法正常工作。 next() 方法工作正常,但调用 show() 没有任何作用。

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();
}

您发布的代码有很多问题,但它不起作用的原因仅仅是您的代码顺序错误。在向 JPanel 添加组件之前,您需要设置其布局管理器。此外,您正在调用错误的 add() 方法。添加其包含的 JPanel 后,仅将带有 CardLayoutJPanel 添加到其父容器。

除此之外,您发布的代码无法编译,因为 class Main 显然扩展了 JFrame 但您发布的代码中缺少它。

您的代码已更正。

import java.awt.CardLayout;
import java.awt.Color;

import javax.swing.JFrame;
import javax.swing.JPanel;

public class Main extends JFrame {
    private static CardLayout cards;
    private static JPanel panel;

    private Main() {
        super("Card Layout");
        setBounds(0, 0, 500, 500);
        setDefaultCloseOperation(3);

        panel = new JPanel();
        cards = new CardLayout();
        panel.setLayout(cards);

        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(p1, "white");
        panel.add(p2, "black");
        panel.add(p3, "red");
        panel.add(p4, "blue");

        // cards.next(panel); This works fine for me.
        cards.show(panel, "red");
        add(panel);

        setVisible(true);
    }

    public static void main(String[] args) {
        new Main();
    }
}

我推荐教程Creating a GUI With JFC/Swing