我已经创建了一个带有一个 JPanel 的类,该 JPanel 将用于 CardLayout,如果我删除注释 // 它在代码底部具有窗口大小,则可以正常工作。它将以这种方式运行,并且一切都运行良好。但是,当我尝试从另一个包含 JFrame 的类中调用它时,它不起作用。
CardDemo.java:
import java.awt.CardLayout;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import java.awt.*;
public class CardDemo extends JPanel implements ListSelectionListener {
CardLayout cl;
JPanel p1, p2, p3, p4, p5;
JList l1;
public CardDemo(){
p1 = new JPanel();
p1.setBackground(Color.red); //the top panel
String[] list1 = { "One", "Two", "Three"};
l1 = new JList(list1);
l1.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
l1.addListSelectionListener(this);
p1.add(l1);
p2 = new JPanel();
p2.setBackground(Color.blue); //bottom panel - we never actually see this
cl = new CardLayout();
p2.setLayout(cl);
p3 = new JPanel();
p3.setBackground(Color.green);
p4 = new JPanel();
p4.setBackground(Color.yellow);
p5 = new JPanel();
p5.setBackground(Color.cyan);
p2.add(p3, "One");
p2.add(p4, "Two");
p2.add(p5, "Three");
//this.setSize(500,400);
//this.setVisible(true);
this.setLayout(new GridLayout(2,2));
this.add(p1);
this.add(p2);
}
/** The actionPerformed method handles button clicks
*/
public void valueChanged(ListSelectionEvent e) {
String listLabel = (String) ((JList)e.getSource()).getSelectedValue(); //get the label of the button that was clicked
cl.show(p2, listLabel); //use the label to display the relevant panel
}
}
测试.java
import javax.swing.*;
import java.awt.*;
public class Test extends JFrame
{
public Test()
{
JFrame frame = new JFrame("CardLayoutDemo");
frame.setDefaultCloseOperation(EXIT_ON_CLOSE);
CardDemo b = new CardDemo();
b.add(frame);
frame.pack();
frame.setVisible(true);
}
}
一切都编译得很好,但是当我运行 Test.java 时,出现以下错误:
java.lang.IllegalArgumentException:向容器添加窗口(在 java.awt.Container 中)
我做错了什么,因为我似乎无法确定它。