Vaadin - Remove Component from its parent
Asked Answered
S

2

5

In the Vaadin framework (v7.1.9), how do we remove a Component from it's parent?

I'm only aware of the removeComponent function, but that requires me to get a handle on the parent (ugly):

ComponentContainer parent = (ComponentContainer) child.getParent();
parent.removeComponent(child);

I tried to just detach the child but that removed it from the 'application' without removing the Component from the UI.

Sondra answered 15/1, 2014 at 20:49 Comment(5)
This is the way to do it.Huehuebner
Why do you think this is ugly? It is like removing an Element from a Collection (HashSet, ArrayList...).Helms
Ok, I like the HashSet/ArrayList comparison. However, when working with HashSet or ArrayList, you don't need to cast. remove is defined in Collection. In Vaadin, removeComponent is defined in ComponentContainer.. but Component.getParent() returns a HasComponents object instead. To me, this is either a flaw in the API or this isn't the way to do what I want to do. What do you guys think?Sondra
honestly I didn't check the interfaces, but it's a good point. I think the reason for this is that some parents are implementing SingleComponentContainer and not HasComponents. Panel for example. But I'm not working on vaadin only using it. May I ask you in what situation you have a component and don't know its parent?Helms
In Java collection comparison how would you get parent collection for a child element? It's totally different situation. I think you should remove components inside your layout class where you will just call removeComponent method without any castsAzote
P
4

if Child is added to Any Layout you should cast it to that layout e.g if child ws added to AbsoluteLayout then

AbsoluteLayout parent = (AbsoluteLayout ) child.getParent();
parent.removeComponent(child);

Try this one

Phenoxide answered 16/1, 2014 at 21:15 Comment(1)
If this Ans Solve your problem then please select it as ANSPhenoxide
F
3

Or like this if child was added to layout.

Layout parent = ( Layout ) child.getParent();
parent.removeComponent(child)

I think this is better than Mubasher solution because it's implementation independent, I mean you don't have to know the Parent layout and if it changes the code still works.

Fructificative answered 16/3, 2016 at 16:56 Comment(1)
My original code is better for the same reason. ComponentContainer is the lowest interface and is what specifies removeComponent, so it's the most robust cast. Still, I've decided it's a Vaadin API flaw that the cast is needed at all. That's the real answer =\Sondra

© 2022 - 2024 — McMap. All rights reserved.