Creating a Simple Component Using the Element API
In this section, we demonstrate how to create a simple 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) . There are constants for most, but not all, tag names.
|
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
|
The @Synchronize annotation can specify multiple events and override the name of the property, if necessary.
|
Note
|
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 address properties and attributes.
Overriding Default Disabled Behavior
The setEnabled
method is available for all components that implement the HasEnabled
interface.
Note
|
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 modify this by overriding the Component:onEnabledStateChanged(boolean)
method.
Example: Overriding the default disabled behavior to ensure items are updated in a component requiring a custom disabled marking.
@Override
public void onEnabledStateChanged(boolean enabled) {
setDisabled(!enabled);
refreshButtons();
}
64ECFAFC-4B33-4E75-8FB2-E7F4B123E70F