Creating a Component Based on Many Elements

There are multiple ways you can create a component. This tutorial uses the Element API and multiple DOM elements. For other component tutorials, see:

You can create a TextField component with support for a label using the following DOM structure:

<div>
    <label></label>
    <input>
</div>

The component class looks like:

@Tag("div")
public class TextField extends Component {

  Element labelElement = new Element("label");
  Element inputElement = new Element("input");

  public TextField() {
      inputElement.synchronizeProperty("value", "change");
      getElement().appendChild(labelElement, inputElement);
  }
}

The DOM structure is set up by marking the root element as a <div> using @Tag("div") and creating and appending a label and an input element to the root element. Value synchronization is set up using the input element, this is an alternative way of synchronisation, the other one can be seen in the basic component tutorial.

You can add API for setting the value of the input and the text of the label, using the corresponding elements:

  public String getLabel() {
      return labelElement.getText();
  }

  public String getValue() {
      return inputElement.getProperty("value");
  }

  public void setLabel(String label) {
      labelElement.setText(label);
  }

  public void setValue(String value) {
    inputElement.setProperty("value", value);
  }