Skip to main content

Beans Binding Converter and Validator Samples

Posted by pkeegan on November 2, 2007 at 5:18 AM PDT

Writing converters and validators for beans binding is not hard. But of course it is much easier to learn how to do so when you have concrete examples in front of you.

The most recent NetBeans daily build has a new sample project that includes custom converters and validators. The sample project is called Client Editor and can be found by choosing File > New Project > Samples > Java. This sample is not in Beta 2, but it will be in the release candidate which is due soon.

Since you might not want wait for the release candidate or final release (or download a nightly build) just to see the sample code, I'll provide an example of a converter and a validator here.

For converters, all you need to do is:

  • Extend org.jdesktop.beansbinding.Converter and pass the source type and target type as parameters.
  • Implement the convertForward and convertReverse methods.

Here is a sample converter that converts an Integer into a String. There is already a default Integer/String converter, but this converter adds the custom behavior of returning 0
if the user does not enter an integer.

import org.jdesktop.beansbinding.Converter;
public class AgeConverter extends Converter {

    public String convertForward(Integer arg) {
        return String.valueOf(arg);
    }

    public Integer convertReverse(String arg) {
        int value;
        try {
            value = (arg == null) ? 0 : Integer.parseInt(arg);
        } catch (NumberFormatException ex) {
            value = 0;
        }
        return value;
    }

}

For validators, it is even simpler:

  • Extend org.jdesktop.beansbinding.Validator and pass the source type to be validated as the parameter.
  • Implement the validate() method.

This example makes sure that an entered age remains with the range of 1 to 199:

import org.jdesktop.beansbinding.Validator;
public class AgeValidator extends Validator {

    public Validator.Result validate(Integer arg) {       
        if ((arg < 1) || (arg > 199)) {
            return new Result(null, "Age range is 1-199");
        }
       
        return null;   
    }
}

Notice how in this case the converter and validator work together. The converter handles a non-integer entry by returning the integer 0, which prevents the user from receiving a generic message that the synchronization failed. Then 0 is passed to the validator, which outputs a more meaningful message ("Age range is 1-199").