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:

HTML

  1. <div>
  2. <label></label>
  3. <input>
  4. </div>

The component class looks like:

Java

  1. @Tag("div")
  2. public class TextField extends Component {
  3. Element labelElement = new Element("label");
  4. Element inputElement = new Element("input");
  5. public TextField() {
  6. inputElement.synchronizeProperty("value", "change");
  7. getElement().appendChild(labelElement, inputElement);
  8. }
  9. }

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:

Java

  1. public String getLabel() {
  2. return labelElement.getText();
  3. }
  4. public String getValue() {
  5. return inputElement.getProperty("value");
  6. }
  7. public void setLabel(String label) {
  8. labelElement.setText(label);
  9. }
  10. public void setValue(String value) {
  11. inputElement.setProperty("value", value);
  12. }