我创建了一个带有一个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
}
}
Test.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);
}
}
Everything编译得很好,但是当我运行Test.java时,我收到以下错误:
java.lang.IllegalArgumentException异常: 向容器添加一个窗口(在java.awt.Container中)
我做错了什么,因为我似乎无法确定它。
答案 0 :(得分:1)
您需要更改
b.add(frame);
到
frame.add(b);
答案 1 :(得分:0)
您正在将JFrame添加到JPanel。它应该是相反的方式。 frame变量引用JFrame,它是顶级窗口。这是所有组件的顶级容器,因此您需要向其中添加组件,而不是相反。