Documentation

Documentation versions (currently viewingVaadin 24)

Creating a Component Using the Element API

Creating a component using a single HTML element.

This section demonstrates how to create a component using the Element API and a single DOM element.

Example: Creating a TextField component based on an <input> element.

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

    public TextField(String value) {
        getElement().setProperty("value",value);
    }
}
  • The root element is:

    • created automatically (by the Component class) based on the @Tag annotation.

    • Accessed using the getElement() method.

    • Used to set the initial value of the field.

Tip
You can use predefined constants in the @Tag annotation. For example, the @Tag("input") annotation is equivalent to @Tag(Tag.INPUT). Most tag names have a constant, but not all.

Adding an API

To make the component easier to use, you can add an API to get and set the value.

Example: Adding an API using the @Synchronize annotation.

@Synchronize("change")
public String getValue() {
    return getElement().getProperty("value");
}
public void setValue(String value) {
    getElement().setProperty("value", value);
}
  • Adding the @Synchronize annotation to the getter ensures that the browser sends property changes to the server.

  • The annotation defines the name of the DOM event that triggers synchronization, in this case a change event.

  • Changes to the input element cause the updated value property (deduced from the getter name) to be sent to the server.

Tip
Using the @Synchronize annotation
The @Synchronize annotation can specify multiple events and override the name of the property, if necessary.
Note
@Synchronize maps events from the root element
The @Synchronize annotation only maps events that originate from the root element, or are bubbled to the root element. For example, if you have an <input> element inside a <div> element, @Synchronize only maps events from the <div> element.

See Using API Helpers to Define Component Properties for an alternative, and simpler, way to manage properties and attributes.

Overriding Default Disabled Behavior

The setEnabled method is available for all components that implement the HasEnabled interface.

Note
Availability of the setEnabled() method
The setEnabled() method is also available for all components that implement the HasValue, HasComponents or Focusable interfaces.

By default, disabling a component adds a disabled property to the client element. You can change this behavior by overriding the Component:onEnabledStateChanged(boolean) method.

Example: Overriding the default disabled behavior to cause items to be updated in a component that has a customized "disabled" indicator.

@Override
public void onEnabledStateChanged(boolean enabled) {
    setDisabled(!enabled);
    refreshButtons();
}

2E20FB94-B5FD-4105-B53B-3EECA329EFF3