gpt4 book ai didi

Java cardLayout 错误的父级

转载 作者:行者123 更新时间:2023-11-30 08:14:18 29 4
gpt4 key购买 nike

我知道这个问题之前已经被问过,但我似乎无法让答案起作用,也不理解它们。

我想做的是交换按钮单击的面板。这是我的主要功能:

public class CreateWindow extends JFrame{

public CreateWindow() {
this.setTitle("Test GUI");

this.putIcon();
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(512, 512);

this.add(new CreatePanel());

this.setVisible(true);
}

这就是我尝试创建面板的地方:

public class CreatePanel extends JPanel implements ActionListener {

JTextArea directoryText;
JFileChooser chooser;
String directory;
ArrayList<File> files;
CardLayout cards;
JPanel panel1, panel2;

public CreatePanel() {
this.setSize(256, 256);
cards = new CardLayout();
this.setLayout(cards);

files = new ArrayList<>();
panel1 = new JPanel(null);
panel2 = new JPanel(null);

this.add(panel1, "panel1");
this.add(panel2, "panel2");
panel1.setBackground(Color.red);
panel2.setBackground(Color.blue);

cards.show(panel1, "panel1");

}
}

我不断收到以下错误:

Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: wrong parent for CardLayout
at java.awt.CardLayout.checkLayout(CardLayout.java:404)
at java.awt.CardLayout.show(CardLayout.java:526)
at jeasussaves.CreatePanel.<init>(CreatePanel.java:54)
at jeasussaves.CreateWindow.<init>(CreateWindow.java:29)
at jeasussaves.JeasusSaves$1.run(JeasusSaves.java:22)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:749)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:702)
at java.awt.EventQueue$3.run(EventQueue.java:696)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:719)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)

最佳答案

CardLayout#show(Container, String) 要求您指定要用作第一个参数的“牌组”,然后指定该牌组中的“卡片”作为第二个参数。

在这种情况下,您的 JPanel (正在扩展的那个)是牌组(因为它是使用 CardLayout 的牌组),而 panel1 是一张牌,因为您已将其添加到牌组中。将 cards.show(panel1, "panel1") 更改为 cards.show(this, "panel1")

添加所有卡片后无需显示您的第一张卡片。您添加的第一张卡是要显示的第一张卡

关于Java cardLayout 错误的父级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29879040/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com