Databinding Converter Example
The following demonstrates a databinding example that uses a converter for a BigDecimal bean property.
The Converter class must extend org.eclipse.core.databinding.conversion.Converter. There would normally be one Converter from Object to String and another one that would work in the opposite direction.
Here’s the code:
public class StringToBigDecimalConverter extends Converter {
public StringToBigDecimalConverter() {
this(String.class, BigDecimal.class);
}
public StringToBigDecimalConverter(Object fromType, Object toType) {
super(fromType, toType);
}
@Override
public Object convert(Object fromObject) {
String from = (String) fromObject;
BigDecimal result = new BigDecimal(0);
try{
result = new BigDecimal(from);
}
catch(Exception ex){
//do nothing
}
return result;
}
}
In SWTDesigner, this converter would be selected in the databinding screen in the target section that corresponds to the SWT control.
SWTDesigner will generate code that binds a bigDecimalText widget to the decimal property of a Bean object. This decimal property is of type BigDecimal.
protected DataBindingContext initDataBindings() {
DataBindingContext bindingContext = new DataBindingContext();
IObservableValue bigDecimalTextObserveTextObserveWidget = SWTObservables.observeText(bigDecimalText, SWT.Modify);
IObservableValue beanDecimalObserveValue = BeansObservables.observeValue(bean, "decimal");
UpdateValueStrategy strategy = new UpdateValueStrategy();
strategy.setConverter(new StringToBigDecimalConverter());
UpdateValueStrategy strategy_1 = new UpdateValueStrategy();
strategy_1.setConverter(new BigDecimalToStringConverter());
bindingContext.bindValue(bigDecimalTextObserveTextObserveWidget, beanDecimalObserveValue, strategy, strategy_1);
return bindingContext;
}
[...] You can do conversion between types with Converters. Take a look at this example. [...]