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

  1. public class TextField extends Composite<Div> {
  2. private Label label;
  3. private Input input;
  4. public TextField(String labelText, String value) {
  5. label = new Label();
  6. label.setText(labelText);
  7. input = new Input();
  8. input.setValue(value);
  9. getContent().add(label, input);
  10. }
  11. }

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

  1. public String getValue() {
  2. return input.getValue();
  3. }
  4. public void setValue(String value) {
  5. input.setValue(value);
  6. }
  7. public String getLabel() {
  8. return label.getText();
  9. }
  10. public void setLabel(String labelText) {
  11. label.setText(labelText);
  12. }

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.