Creating a Simple Component Using the Element API

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

You can create a simple TextField component based on an <input> element as follows:

Java

  1. @Tag("input")
  2. public class TextField extends Component {
  3. public TextField(String value) {
  4. getElement().setProperty("value",value);
  5. }
  6. }

The Component class will automatically create its root element based on the @Tag annotation, which can then be accessed using getElement(). The root element in the text field is in this example used to set the initial value of the field.

Tip
You can use predefined constants in the @Tag annotation. E.g. the annotation @Tag(“input”) is equivalent to @Tag(Tag.INPUT). But those constants don’t cover all possible tag names.

To make the component easier to use, you can add an API for getting and setting the value:

Java

  1. @Synchronize("change")
  2. public String getValue() {
  3. return getElement().getProperty("value");
  4. }
  5. public void setValue(String value) {
  6. getElement().setProperty("value", value);
  7. }

To make the framework send property changes from the browser to the server, an @Synchronize annotation is added to the getter. The annotation defines the name of DOM event which triggers synchronization, i.e. in this case a change event from the input element will cause the updated value property (deduced from the getter name) to be sent to the server.

Tip
The @Synchronize annotation can specify multiple events and override the name of the property if needed.
Note
The @Synchronize annotation maps events originated from the root element of the webcomponent only (or events bubbled to the root element). If you have a <div> as the root element and an <input> inside it, the only events that can be mapped using @Synchronize are the events from the <div> element.
Tip
For an easier way to address properties and attributes, see Using API Helpers for Defining Component Properties

Component Enabled

The setEnabled method will be available for any component implementing the HasEnabled interface (which comes also with HasValue, HasComponents and Focusable).

By default disabling the component will add a disabled property to the client element, but this can be modified by overriding Component:onEnabledStateChanged(boolean) method.

For instance if the component requires a custom disabled marking and that its items get updated the override could be created as:

Java

  1. @Override
  2. public void onEnabledStateChanged(boolean enabled) {
  3. setDisabled(!enabled);
  4. refreshButtons();
  5. }