Docs

Documentation versions (currently viewingVaadin 24)

Creating a Component Using Existing Components

Creating a component by combining existing components together.

This section demonstrates how to create a Composite component using existing components.

The example creates 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’s possible to create a new component by extending the Div HTML component, but this isn’t 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, specifying it by using generics (Composite<Div>).

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

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

  • 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. You 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 doesn’t result in extra overhead.

6047C25F-34E4-4192-BAAF-D9057BF74F0D