You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

CreatingATextFieldForIntegerOnlyInputWhenNotUsingADataSource.asciidoc 1.8KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  1. ---
  2. title: Creating A Text Field For Integer Only Input When Not Using A Data Source
  3. order: 23
  4. layout: page
  5. ---
  6. [[creating-a-textfield-for-integer-only-input-when-not-using-a-data-source]]
  7. = Creating a TextField for integer only input when not using a data source
  8. A `TextField` is a component that always has a value of type `String`. By
  9. adding a converter to a field, the field will automatically validate
  10. that the entered value can be converted and it will provide the
  11. converted value using the `getConvertedValue()` method.
  12. [source,java]
  13. ....
  14. final TextField textField = new TextField("Text field");
  15. textField.setConverter(Integer.class);
  16. Button submitButton = new Button("Submit value", new ClickListener() {
  17. public void buttonClick(ClickEvent event) {
  18. String uiValue = textField.getValue();
  19. try {
  20. Integer convertedValue = (Integer) textField
  21. .getConvertedValue();
  22. Notification.show(
  23. "UI value (String): " + uiValue
  24. + "<br />Converted value (Integer): "
  25. + convertedValue);
  26. } catch (ConversionException e) {
  27. Notification.show(
  28. "Could not convert value: " + uiValue);
  29. }
  30. }
  31. });
  32. addComponent(new Label("Text field type: " + textField.getType()));
  33. addComponent(new Label("Converted text field type: "
  34. + textField.getConverter().getModelType()));
  35. addComponent(textField);
  36. addComponent(submitButton);
  37. ....
  38. With this example, entering a number and pressing the button causes the
  39. value of the `TextField` to be a `String` while the converted value will be
  40. an `Integer` representing the same value. If e.g. a letter is entered to
  41. the field and the button is pressed, the validation will fail. This
  42. causes a notice to be displayed for the field and an exception to be
  43. thrown from `getConvertedValue()`.