Creating a TextField for integer only input using a data source

A TextField is a component that always has a value of type String. When binding a property of another type to a text field, the value is automatically converted if the conversion between the two types is supported.

Java

  1. public class MyBean {
  2. private int value;
  3. public int getValue() {
  4. return value;
  5. }
  6. public void setValue(int integer) {
  7. value = integer;
  8. }
  9. }

The property named “value” from a BeanItem constructed from MyBean will be of type Integer. Binding the property to a TextField will automatically make validation fail for texts that can not be converted to an Integer.

Java

  1. final MyBean myBean = new MyBean();
  2. BeanItem<MyBean> beanItem = new BeanItem<MyBean>(myBean);
  3. final Property<Integer> integerProperty = (Property<Integer>) beanItem
  4. .getItemProperty("value");
  5. final TextField textField = new TextField("Text field", integerProperty);
  6. Button submitButton = new Button("Submit value", new ClickListener() {
  7. public void buttonClick(ClickEvent event) {
  8. String uiValue = textField.getValue();
  9. Integer propertyValue = integerProperty.getValue();
  10. int dataModelValue = myBean.getValue();
  11. Notification.show("UI value (String): " + uiValue
  12. + "\nProperty value (Integer): " + propertyValue
  13. + "\nData model value (int): " + dataModelValue);
  14. }
  15. });
  16. addComponent(new Label("Text field type: " + textField.getType()));
  17. addComponent(new Label("Text field type: " + integerProperty.getType()));
  18. addComponent(textField);
  19. addComponent(submitButton);

With this example, entering a number and pressing the button causes the value of the TextField to be a String, the property value will be an Integer representing the same value and the value in the bean will be the same int. If e.g. a letter is entered to the field and the button is pressed, the validation will fail. This causes a notice to be displayed for the field. The field value is still updated, but the property value and the bean value are kept at their previous values.