Documentation

Documentation versions (currently viewingVaadin 23)

Creating a Component Using Existing Components

In this section, we demonstrate how to create a Composite component using existing components.

We create a TextField component by combining existing Div, Label and Input HTML components into this hierarchy:

  • Div

    • Label

    • Input

Note
Create the component based on a Composite
Creating the component based on a Composite is the best practice in these circumstances. It is possible to create a new component by extending the Div HTML component, but this is not advisable, because it unnecessarily exposes Div API methods, such as add(Component), to the user.

Example: Creating a TextField component by extending Composite<Div>.

public class TextField extends Composite<Div> {

    private Label label;
    private Input input;

    public TextField(String labelText, String value) {
        label = new Label();
        label.setText(labelText);
        input = new Input();
        input.setValue(value);

        getContent().add(label, input);
    }
}
  • The Composite automatically creates the root component. We specify this by using generics (Composite<Div>).

  • We can access the root component through the getContent() method.

  • In the constructor, we only need to create the child components and add them to the root Div.

  • We set the value by using setValue() method in the Input component.

Adding an API

To make the component easier to use, you can add an API to get and set the value and label text. We do this by delegating to the Input and Label components.

Example: Adding an API to get and set the value and label.

public String getValue() {
    return input.getValue();
}
public void setValue(String value) {
    input.setValue(value);
}

public String getLabel() {
    return label.getText();
}
public void setLabel(String labelText) {
    label.setText(labelText);
}
  • The public API only exposes the defined methods, and a few generic methods defined in the Component interface.

Tip
Keeping overhead to a minimum
Using a Component (instead of an Element) or a Composite does not result in extra overhead.

6047C25F-34E4-4192-BAAF-D9057BF74F0D