Component Containers
- Using the
HasComponentsInterface - Implementing a Custom Add Method
- Navigating the Component Hierarchy
- Removing Child Components
A component container is a component to which you can add other components.
Using the HasComponents Interface
You typically create a container by implementing the HasComponents interface. This interface provides add(Component…​) and remove(Component…​) methods for attaching and detaching child components to and from the container’s root element.
Source code
Java
@Tag("div")
public class MyComponentContainer extends Component implements HasComponents {
}Implementing a Custom Add Method
You can also implement your own methods for adding and removing child components. In this case, you interact with the container’s root element directly through the getElement() method.
Source code
Java
@Tag("div")
public class MyComponentContainer extends Component {
public void add(Component child) {
getElement().appendChild(child.getElement());
}
}You don’t need to add a child component directly to the container’s root element. You can add it to any element in the container’s element hierarchy.
<div> elementSource code
Java
@Tag("div")
public class MyComponentContainer extends Component {
public void add(Component child) {
Element childWrapper = ElementFactory.createDiv();
childWrapper.appendChild(child.getElement());
getElement().appendChild(childWrapper);
}
}Navigating the Component Hierarchy
The component hierarchy is directly based on the element hierarchy in the DOM tree. You can access a component’s parent element using the getElement().getParent() method, and the child elements using the getElement().getChildren() method.
If you need access to the components themselves and not only their elements, use the Component.getParent() and Component.getChildren() methods.
Removing Child Components
You remove a component by detaching its element from the container. You typically do this by calling the Element.removeFromParent() method on the child component’s element.
You can also remove a child component by adding its element to another component. This effectively moves the element from the old parent to the new one.
removeFromParent() method to remove a child componentSource code
Java
@Tag("div")
public class MyComponentContainer extends Component {
public void add(Component child) {
Element childWrapper = ElementFactory.createDiv();
childWrapper.appendChild(child.getElement());
getElement().appendChild(childWrapper);
}
public void remove(Component child) {
Element wrapper = child.getElement().getParent();
wrapper.removeFromParent();
}
}|
Tip
|
Detecting when a child component is removed
If you need to know when a child component is removed, add a detach listener to it using the Component.addDetachListener() method. See Vaadin Component Basics for more information.
|
B669953B-4FB8-4B0F-920A-67AAC655BBD2