Creating a TextField for integer only input when not using a data source

A TextField is a component that always has a value of type String. By adding a converter to a field, the field will automatically validate that the entered value can be converted and it will provide the converted value using the getConvertedValue() method.

Java

  1. final TextField textField = new TextField("Text field");
  2. textField.setConverter(Integer.class);
  3. Button submitButton = new Button("Submit value", new ClickListener() {
  4. public void buttonClick(ClickEvent event) {
  5. String uiValue = textField.getValue();
  6. try {
  7. Integer convertedValue = (Integer) textField
  8. .getConvertedValue();
  9. Notification.show(
  10. "UI value (String): " + uiValue
  11. + "<br />Converted value (Integer): "
  12. + convertedValue);
  13. } catch (ConversionException e) {
  14. Notification.show(
  15. "Could not convert value: " + uiValue);
  16. }
  17. }
  18. });
  19. addComponent(new Label("Text field type: " + textField.getType()));
  20. addComponent(new Label("Converted text field type: "
  21. + textField.getConverter().getModelType()));
  22. addComponent(textField);
  23. addComponent(submitButton);

With this example, entering a number and pressing the button causes the value of the TextField to be a String while the converted value will be an Integer representing the same value. 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 and an exception to be thrown from getConvertedValue().