Composition with CustomComponent

The ease of making new user interface components is one of the core features of Vaadin. Typically, you simply combine existing built-in components to produce composite components. In many applications, such composite components make up the majority of the user interface.

As described earlier in “Compositing Components”, you have two basic ways to create a composite - either by extending a layout component or the CustomComponent, which typically wraps around a layout component. The benefit of wrapping a layout composite in CustomComponent is mainly encapsulation - hiding the implementation details of the composition. Otherwise, a user of the composite could rely on implementation details, which would create an unwanted dependency.

To create a composite, you need to inherit the CustomComponent and set the composition root component in the constructor. The composition root is typically a layout component that contains other components.

For example:

Java

  1. class MyComposite extends CustomComponent {
  2. public MyComposite(String message) {
  3. // A layout structure used for composition
  4. Panel panel = new Panel("My Custom Component");
  5. VerticalLayout panelContent = new VerticalLayout();
  6. panelContent.setMargin(true); // Very useful
  7. panel.setContent(panelContent);
  8. // Compose from multiple components
  9. Label label = new Label(message);
  10. label.setSizeUndefined(); // Shrink
  11. panelContent.addComponent(label);
  12. panelContent.addComponent(new Button("Ok"));
  13. // Set the size as undefined at all levels
  14. panelContent.setSizeUndefined();
  15. panel.setSizeUndefined();
  16. setSizeUndefined();
  17. // The composition root MUST be set
  18. setCompositionRoot(panel);
  19. }
  20. }

Take note of the sizing when trying to make a customcomponent that shrinks to fit the contained components. You have to set the size as undefined at all levels; the sizing of the composite component and the composition root are separate.

You can use the component as follows:

Java

  1. MyComposite mycomposite = new MyComposite("Hello");

The rendered component is shown in A custom composite component.

customcomponent example1

A custom composite component

You can also inherit any other components, such as layouts, to attain similar composition. Even further, you can create entirely new low-level components, by integrating pure client-side components or by extending the client-side functionality of built-in components. Development of new components is covered in “Integrating with the Server-Side”.