Re: Copying JPanel components to another JPanel
- From: Thomas Fritsch <i.dont.like.spam@xxxxxxxxxxx>
- Date: Tue, 14 Aug 2007 16:31:15 GMT
marcussilfver@xxxxxxxxx schrieb:
I want to copy the contents of a jPanel to another JPanel, then I wantAdding a Component to a Container (in this case: to jp) has a side-effect. The Component is first removed from its previous parent, if it is a child of any parent (in this case: of jPanel1). AWT does it that way, to ensure that a child will never belong to more than one parent simultaneously. This behaviour is well-hidden described in the API doc of java.awt.Container#addImpl.
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));
For you this means, that after your "add" operation, the "numComponents" had become wrong, because the actual number of components now has got smaller by 1. Also the numbering of components in jPanel1 has changed.
}Try something like this:
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?
int numComponents = jPanel1.getComponentCount();
for (int i = 0; i < numComponents; i++)
{
jp.add(jPanel1.getComponent(0));
//jPanel1.remove(...) isn't needed, because child is already removed
}
or may be like this:
for (int i = jPanel1.getNumComponents() - 1; i >= 0; i--)
{
jp.add(jPanel1.getComponent(i));
//jPanel1.remove(...) isn't needed, because child is already removed
}
--
Thomas
.
- Follow-Ups:
- Re: Copying JPanel components to another JPanel
- From: bcr666
- Re: Copying JPanel components to another JPanel
- References:
- Copying JPanel components to another JPanel
- From: marcussilfver
- Copying JPanel components to another JPanel
- Prev by Date: Copying JPanel components to another JPanel
- Next by Date: hooking up arrays of Listeners
- Previous by thread: Copying JPanel components to another JPanel
- Next by thread: Re: Copying JPanel components to another JPanel
- Index(es):
Relevant Pages
|
|