Changing the default converters for an application

Each Vaadin session instance has a ConverterFactory that provides converters to Fields and Table. The defaults might not be ideal for your case so it is possible for you to change the defaults by providing your own ConverterFactory. If you, for instance, want to format all (or most) doubles from your data model with 3 decimals and no thousand separator (but still allow the user to input with any number of decimals) you can do this by first creating your own Converter:

Java

  1. public class MyStringToDoubleConverter extends StringToDoubleConverter {
  2. @Override
  3. protected NumberFormat getFormat(Locale locale) {
  4. NumberFormat format = super.getFormat(locale);
  5. format.setGroupingUsed(false);
  6. format.setMaximumFractionDigits(3);
  7. format.setMinimumFractionDigits(3);
  8. return format;
  9. }
  10. }

and then extending the default converter factory to use your converter for all Double <-> String conversions.

Java

  1. public class MyConverterFactory extends DefaultConverterFactory {
  2. @Override
  3. protected <PRESENTATION, MODEL> Converter<PRESENTATION, MODEL> findConverter(
  4. Class<PRESENTATION> presentationType, Class<MODEL> modelType) {
  5. // Handle String <-> Double
  6. if (presentationType == String.class && modelType == Double.class) {
  7. return (Converter<PRESENTATION, MODEL>) new MyStringToDoubleConverter();
  8. }
  9. // Let default factory handle the rest
  10. return super.findConverter(presentationType, modelType);
  11. }
  12. }

You still need to tell your application to always use MyConverterFactory:

Java

  1. VaadinSession.getCurrent().setConverterFactory(new MyConverterFactory());

Now we can test it using

Java

  1. public class MyUI extends UI {
  2. public void init(VaadinRequest request) {
  3. TextField tf = new TextField("This is my double field");
  4. tf.setImmediate(true);
  5. tf.setConverter(Double.class);
  6. setContent(tf);
  7. tf.setConvertedValue(50.1);
  8. }
  9. }

This will not enforce the contents of the field to the format specified by the converter. Only data from the data source is formatted to adhere to the format set in the converter.

If you want to force the user to enter data with a given number of decimals you need to create your own converter instead of only overriding the format for StringToDoubleConverter.