如何使 CardLayout 使用任意数量的卡片?

How do I make a CardLayout work with an arbitrary amount of cards?

我正在尝试使 cardLayout 与任意数量的卡片一起工作,这意味着我将需要某种循环遍历我拥有的所有对象。现在我尝试了,我让它与手动创建的 JPanel 一起工作,但是一旦我在其中放置一个循环,它就不起作用了。

@SuppressWarnings("serial")

public class ClassCardLayoutPane extends JPanel{

JPanel cards;

public ClassCardLayoutPane() {
    initialiseGUI();
}

private void initialiseGUI() {
    String[] listElements = {"A2", "C3"};
    cards = new JPanel(new CardLayout());


    JLabel label = new JLabel("Update");
    add(label);

    JList selectionList = new JList(listElements);
    selectionList.addListSelectionListener(new ListSelectionListener() {

        @Override
        public void valueChanged(ListSelectionEvent evt) {

            if (!evt.getValueIsAdjusting()) {
                label.setText(selectionList.getSelectedValue().toString());
                CardLayout cl = (CardLayout)(cards.getLayout());
                cl.show(cards, label.getText());


            }
        }

    });

    // The panels created by this loop don't work, the cards get stuck on the first one

    /*
    for (int i = 0; i < listElements.length-1; i ++) {

        JPanel temp = new JPanel();
        temp.add(new JLabel(i+""));
        cards.add(temp, listElements[i]);

    }*/


    JPanel card1 = new JPanel();
    card1.add(new JTable(20,20));

    JPanel card2 = new JPanel();
    card2.add(new JTable(10,20));

    cards.add(card1, listElements[0]);
    cards.add(card2, listElements[1]);

    //the panels here do work. I don't know what I'm doing wrong

    add(selectionList);
    add(cards);
}

public static void main(String[] args) {
    JFrame main = new JFrame("Win");
    main.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    main.setPreferredSize(new Dimension(1366, 768));
    main.getContentPane().add(new ClassCardLayoutPane());
    main.pack();
    main.setVisible(true);
}

}

好吧,注释掉的循环是什么对我不起作用,这让我很困惑?有人可以向我解释为什么它不起作用以及我如何让它起作用吗?顺便说一句,listElements 可以有不同的大小,这就是我正在努力工作的原因,因为最终 listElements 将作为一个 LinkedList 开始,所以当我为 ListItems 创建数组时,它每次都会有不同的大小,因为我不知道会有多少项目。有人可以帮我完成这项工作吗? "It doesn't work",我的意思是当我使用循环时,JPanel 卡在第一张卡片上并且不再切换到下一张卡片!没有错误消息,程序运行正常,但它没有执行其预期的操作,即切换卡!请注意,当我单独执行它们时,程序运行完美!谢谢。

Okay so the commented out for loop is what doesn't work for me which has me really confused?

那么您应该做的第一件事就是将调试代码添加到循环中以查看是否正在使用唯一的卡片名称。

如果这样做,您会注意到以下问题:

for (int i = 0; i < listElements.length-1; i ++) {

为什么要从列表长度中减去 1?您只能将一个面板添加到 CardLayout。

代码应该是:

for (int i = 0; i < listElements.length; i ++) {

当代码没有像您认为的那样执行时,您需要添加调试代码或使用调试器单步执行代码以查看代码是否按预期执行。

你不能总是盯着代码看。