Creating a Component Using Existing Components
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 CompositeCreating the component based on a Compositeis the best practice in these circumstances.
It’s possible to create a new component by extending theDivHTML component, but this isn’t advisable, because it unnecessarily exposesDivAPI methods, such asadd(Component), to the user. | 
Example: Creating a TextField component by extending Composite<Div>.
Source code
Java
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 Compositeautomatically 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 theInputcomponent.
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.
Source code
Java
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 minimumUsing a Component(instead of anElement) or aCompositedoesn’t result in extra overhead. | 
6047C25F-34E4-4192-BAAF-D9057BF74F0D