java 中 CardLayout 的父级错误

wrong parent for CardLayout in java

我想为组合框中的每个选项更改 CardLayout(包含标签)中的卡片。因此,当我在组合框中 select Item2 时,它应该显示第二张卡片,但它 returns 错误。

在方法 initComponents() 中,我使用 cardLayout.show(imagePanel, "1");[=19= 成功显示了第一张卡片] 但是当我尝试在 private void comboMenuActionPerformed() 中做同样的事情时,它 returns 错误 "IllegalArgumentException: wrong parent for CardLayout"。为什么会这样?

public class MyFrame extends JFrame {
    public MyFrame() {
        initComponents();
    }
    private void initComponents() {
        cardLayout = new java.awt.CardLayout(); 
        mainPanel = new javax.swing.JPanel();
        centerPanel = new javax.swing.JPanel();
        imagePanel = new javax.swing.JPanel(cardLayout);
        comboMenu = new javax.swing.JComboBox<>();
        JLabel firstPicture = new JLabel("");
        JLabel secondPicture = new JLabel("");
        ...

        firstPicture.setIcon(...);
        secondPicture.setIcon(...); 

        imagePanel.add(firstPicture, "1");
        imagePanel.add(secondPicture, "2");
        String[] menu = {"Item1", "Item2", "Item3"};

        cardLayout.show(imagePanel, "1"); //this works fine

        imagePanel.setLayout(new java.awt.CardLayout());
        centerPanel.add(imagePanel);

        comboMenu.setModel(new javax.swing.DefaultComboBoxModel<>(menu));

        mainPanel.add(centerPanel);
    }

    private void comboMenuActionPerformed(java.awt.event.ActionEvent evt) {                                           
        if(comboMenu.getSelectedItem().toString().equals("Item2")) {
            cardLayout.show(imagePanel, "2"); //WHY THIS DOESN'T WORK
        }
    }

    public static void main(String args[]) {
            java.awt.EventQueue.invokeLater(new Runnable() {
                public void run() {
                    new MyFrame().setVisible(true);
                }
        });
    }
    private javax.swing.JComboBox<String> comboMenu;
    private javax.swing.JPanel centerPanel;
    private javax.swing.JPanel imagePanel;
    private javax.swing.JPanel mainPanel;
    private java.awt.CardLayout cardLayout;
}
    imagePanel = new javax.swing.JPanel(cardLayout);
    ...
    cardLayout.show(imagePanel, "1"); //this works fine
    imagePanel.setLayout(new java.awt.CardLayout());

您将图像面板的布局替换为 CardLayout 的新实例。去掉最后一条语句:

    //imagePanel.setLayout(new java.awt.CardLayout());

您通过以下方式将卡片布局分配给 imagePanel

imagePanel = new javax.swing.JPanel(cardLayout);

然后您通过以下方式分配新的卡片布局:

imagePanel.setLayout(new java.awt.CardLayout());

这会覆盖您添加标签的第一个卡片布局。