Creating a Component Using Existing Components
There are multiple ways you can create a component. This tutorial uses a Composite
to construct a new component using existing components. For other component tutorials, see:
A TextField can be created by combining the existing HTML components Div
, Label
and Input
into the following hierarchy:
Div
Label
Input
One option would be to create the component by extending Div
but that would expose all Div
API like add(Component)
to the user. To avoid this, the component can be based on a Composite
:
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);
}
}
A Composite will automatically create the root component, specified using generics (Composite<Div>
) and make it available through getContent(). In the constructor you only need to create the other components and add them to the root Div
. The value is set using setValue
in the Input
component.
To make the component easier to use, you can add an API for getting and setting the value and the label text by delegating to the Input
and Label
components:
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 of TextField only contains the defined methods in addition to the few generic methods defined in the Component
interface.
Tip | Using a Composite does not introduce overhead in the browser. |
Tip | Using Components instead of Elements do not introduce overhead in the browser. |