Dynject and Swing

back to index

Dynject comes with built-in support for most of the Swing standard components. A typical use scenario is as follows. You have a user form like :

Swing Form

In this example, the customer name and birthdate fields are JTextFields, whereas the discount rate is a JSpinner control. However, the components themselves are irrelevant, as dynject can handle many other swing components.

Usually, you'd have to read the data from these components (using getText(), getValue(), etc), perform whatever validations are needed and finally pass the value to the final object. With dynject, most of the process is automated.

After creating the form you annotate your model using dyjnect annotations:


import java.util.Calendar;
import com.planetalia.dynject.preprocess.*;
import com.planetalia.dynject.validation.*;
public class Customer {
  @Normalized(
     whitespace=WhitespaceProcessing.COLLAPSE,
     trim=TrimType.BOTH,
     transform=TransformType.UPPERCASE
   )
   @Length( min=3,max=20,
            message="Customer length must be between 3 and 20 characters")
   public String customer;


   @IsDate( value="dd/MM/yyyy", message="The birth date must be a valid date in dd/MM/yyyy format")
   public Calendar birthdate;
  
   @MinInclusive(value=0,message="The discount cannot be less than 0")
   @MaxInclusive(value=20,message="The discount cannot be greater than 20")
   public int discount;
}

Here we are saying that:

So once that you have the annotated model, reading and validating the user input is as simple as:

Customer customer = new Customer();
ErrorMap errorMap= Shell.assign(customer, new SwingSource(swingForm));

Where swingForm is the instance of the swing JForm that contains the components.

The assign method extracts all needed properties, validates the data, generates errror messages for those pieces of data that are incorrect and stores the correct ones into the appropriate fields, performing whatever conversions are necessary to match the data types (for example, from String to Calendar as in the case of birthdate).

There's only one requirement for this to work automatically

Here are the sources for the full example:

And here's a sample result :

Dynject validated swing form