Copying JPanel components to another JPanel



I want to copy the contents of a jPanel to another JPanel, then I want
to empty the original JPanel.
I unsuccessfully tried the following:

jPanel1 = new JPanel();
jPanel1.setBounds(371, 112, 364, 28);
jPanel1.add(new JLabel("a"));
jPanel1.add(new JLabel("b"));
jPanel1.add(new JLabel("c"));

JPanel jp = new JPanel();

int numComponents = jPanel1.getComponentCount();
System.out.println("Number of components in jPanel1 is " +
numComponents);

for (int i=0; i<numComponents; i++)
{
jp.add(jPanel1.getComponent(i));
}
jPanel1.removeAll();

But I get an error like this
java.lang.ArrayIndexOutOfBoundsException: No such child: 2
at java.awt.Container.getComponent(Unknown Source)...

NOTE:
If I replace the row inside the loop with the following row:
System.out.println(jPanel1.getComponent(i).toString());

then I dont get an exception in getComponent, I then get a correct
standard out to the console!

So how can I achieve copying JPanel components? Am I way off?

.



Relevant Pages

  • Re: Copying JPanel components to another JPanel
    ... to empty the original JPanel. ... int numComponents = jPanel1.getComponentCount; ... The Component is first removed from its previous parent, if it is a child of any parent ...
    (comp.lang.java.gui)
  • Embedding SWING/JPanel in SWT
    ... I'm trying to embed a a data plotting class in a simple SWT ... JPanel holding a couple of controls and the result is always an empty ... final Shell shell = new Shell; ...
    (comp.lang.java.gui)
  • Simple GridBagLayout Question
    ... I have a JPanel with a GridBagLayout. ... the column with text is wider than the other one. ... However, when they both contain equal text, or both are empty, they ...
    (comp.lang.java.programmer)