如何将Character绑定到TextField?

时间:2018-07-31 11:21:36

标签: vaadin vaadin10

我找到了一个如何将Integer绑定到TextField的示例:

Binder<Person> b = new Binder<>();
b.forField(ageField)
    .withNullRepresentation("")
    .withConverter(new StringToIntegerConverter("Must be valid integer !"))
    .withValidator(integer -> integer > 0, "Age must be positive")
    .bind(p -> p.getAge(), (p, i) -> p.setAge(i));

问题是-没有StringToCharacterConverter,如果按原样绑定字段,是否有错误。错误是:

Property type 'java.lang.Character' doesn't match the field type 'java.lang.String'. Binding should be configured manually using converter.

1 个答案:

答案 0 :(得分:3)

您需要实现自定义转换器,这是StringToCharacterConverter的非常简化的版本,用于获取其外观如下:

public class StringToCharacterConverter implements Converter<String,Character> {

    @Override
    public Result<Character> convertToModel(String value, ValueContext context) {
        if (value == null) {
            return Result.ok(null);
        }

        value = value.trim();

        if (value.isEmpty()) {
            return Result.ok(null);
        } else if (value.length() == 1) {
            Character character = value.charAt(0);
            return Result.ok(character);
        } else {
            return Result.error("Error message here");
        }
    }

    @Override
    public String convertToPresentation(Character value, ValueContext context) {
        String string = value.toString();
        return string;
    }

}