问题
I want to change cards in my CardLayout (which contains labels) for every choice in my combo box. So when I select Item2 in the combo box it should show the second card but it returns error instead.
Inside the method initComponents() I successfully showed the first card using cardLayout.show(imagePanel, "1"); but when I tried to do the same inside private void comboMenuActionPerformed(), it returns the error "IllegalArgumentException: wrong parent for CardLayout". Why is this happening?
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;
}
回答1:
imagePanel = new javax.swing.JPanel(cardLayout);
...
cardLayout.show(imagePanel, "1"); //this works fine
imagePanel.setLayout(new java.awt.CardLayout());
You replace the layout of the image panel with a new instance of the CardLayout. Get rid of the last statement:
//imagePanel.setLayout(new java.awt.CardLayout());
回答2:
You assign the card layout to imagePanel
by:
imagePanel = new javax.swing.JPanel(cardLayout);
But then you assign a new card layout by:
imagePanel.setLayout(new java.awt.CardLayout());
This overwrites the first card layout to which you added the labels.
来源:https://stackoverflow.com/questions/60611409/wrong-parent-for-cardlayout-in-java