tags:

views:

96

answers:

1

What I'm trying to achive is basically the "Enclose in" feature of Netbeans at runtime:

Let's say I have this component hierarchy:

Container
    Label 1
    Label 2
    Label 3

And I want to enclose Label 2 like this:

Container
    Label 1
    Container
        Label 2
    Label 3

And I also want to revert it, i.e. I want to "pull up" the label again to get the original hierarchy.

EDIT: The problem is that at runtime I only know Label 2. Any other components (siblings, parents, children) are unknown. That eliminates the possibitlity to just reconstruct the hierarchy.

Of couse I'm sure I can find some way to get this functionality by traversing the component hierarchies, but I wonder:

Is there a better way? Perhaps some kind of utility class which provides this encapsulation feature?

EDIT 2: How do I get the layout constraints the component originally was added to the container? I need this information because the new container has to use the same constraints. Also when restoring the original hierarchy the component has to re-use its old constraints.

+1  A: 

Containers are Components as well, so it is possible to enclose Containers in Containers.

So, perhaps the first state would be something along the line of (pseudocode):

Container container1 = new Container();
Label label1 = new Label();
Label label2 = new Label();
Label label3 = new Label();
container1.add(label1);
container1.add(label2);
container1.add(label3);

To transition to the second state:

Container container2 = new Container();
container1.remove(label2);
container2.add(label2);
container2.add(container1);

Now, the label2 is moved into container2 and that container itself is contained in container1.

And to return to the original state:

container2.remove(label2);
container1.add(label1);
container1.remove(container2);

Edit

If all we know is label2 itself, that is already contained in some Container, we can determine the parent Container by calling the Component's getParent() method.

Applying that to the code above, replace the line for making container1 with the following:

Container container1 = label2.getParent();

If you want to get the Components which are held in the Container, the getComponents() method can be called in order to retrieve an array of Components.

coobird
Oh, I'm sorry, I noticed that my question is very ambiguous. I will clarify...
DR
OK, that was way easier than I thought. For some reason I was convinced that I have to maintain the original order of the children to keep the layout but then I realized that the order has nothing to do with it... *doh*.
DR
Visual ordering of the components are going to be the job of the LayoutManager, which is of course a big topic in itself!
coobird
Yeah, normally I'd know... Lack of sleep or caffeine... or both :)
DR
How do I get the constraints the component was added to the container? Because the enclosing component has to get the same.
DR