如何将 Character 绑定到 TextField?
How do I bind Character to a TextField?
我找到了一个如何将 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.
您需要实施自定义转换器,这里是非常简化的版本,可以是 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;
}
}
我找到了一个如何将 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.
您需要实施自定义转换器,这里是非常简化的版本,可以是 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;
}
}