Docs

Documentation versions (currently viewingVaadin 14)

You are viewing documentation for an older Vaadin version. View latest documentation

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
Creating the component based on a Composite is the best practice in these circumstances. While it is possible to create a new component by extending the Div HTML component, 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 (specified using generics (Composite<Div>)).

  • The root component is available through the getContent() method.

  • In the constructor, it is only necessary to create the child components and add them to the root Div.

  • The value is set using the 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, 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
Neither using a Component (instead of an Element), nor using a Composite, introduces additional overhead in the browser.

4429671A-23AB-4151-9D32-E93DDA52C4A8