问题描述
我想为我的组合框中的每个选择更改CardLayout(包含标签)中的卡片.因此,当我在组合框中选择Item2时,它应该显示第二张卡片,但它返回错误.
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.
在方法 initComponents()中,我成功地使用 cardLayout.show(imagePanel,"1"); 显示了第一张卡,但是当我尝试在内部进行相同操作时 private void comboMenuActionPerformed(),它返回错误"IllegalArgumentException:CardLayout的父级错误".为什么会这样?
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;
}
推荐答案
imagePanel = new javax.swing.JPanel(cardLayout);
...
cardLayout.show(imagePanel, "1"); //this works fine
imagePanel.setLayout(new java.awt.CardLayout());
用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());
这篇关于Java中CardLayout的错误父代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!