I have created a class with one JPanel which will be used for the CardLayout, this works fine if I remove the comment // which has the window size at the bottom of the code. It will run that way and everything functions perfectly. However when I try to call it from another class which has a JFrame in it, it doesn't work.
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 compiles just fine, but when I run Test.java I get the following error:
java.lang.IllegalArgumentException: adding a window to a container (in java.awt.Container)
What is it that I am doing wrong as I can't seem to pinpoint it.
You need to change
b.add(frame);
to
frame.add(b);