Monday, August 15, 2011

Creating Swing Forms Using JFormPane

JFormPane is a class that allows to create swing forms fast and easily. Let's see how it's done by creating an example where we collect user info:


Creating the form fields

Whenever we want to create a form, we must create the fields that are part of that form first, to achive this, we use the FormField class. We are going to create six FormField objects to collect the user first name, last name, password, weight, birthday and to find out is he/she likes ice-cream:
FormField firstNameField = new FormField("First Name", FormField.Type.TEXT);
FormField lastNameField = new FormField("Last Name");
FormField passwordField = new FormField("Password", FormField.Type.PASSWORD);
FormField birthdayField = new FormField("Birthday", FormField.Type.DATE);
FormField weightField = new FormField("Weight", FormField.Type.NUMBER);
FormField iceCreamField = new FormField("Likes Ice-cream?", FormField.Type.BOOLEAN);
As seen in the example above, the FormField class constructor takes two parameters: the name of the field, and the type of the field. If you ommit the type of the field, the FormField class will set it to text.

Creating a new JFormPane

We then add the form fields to an array. That array is the one we pass to the FormField constructor.
FormField[] fields = {
	firstNameField,
	lastNameField,
	passwordField,
	birthdayField,
	weightField,
	iceCreamField
};

JFormPane formPane = new JFormPane(fields);
JOptionPane.showMessageDialog(null, formPane);
This will give us a shiny new form as the one below:


Reading the form values

To read the form values we use the getValues() method, that will return an Object array. Once we read the values, we can cast the results into their original type, as follows:
Object[] results = formPane.getValues();

String firstName = (String) results[0];
String lastName = (String) results[1];
String password = (String) results[2];
Date birthday = (Date) results[3];
Double weight = (Double) results[4];
Boolean likesIceCream = (Boolean) results[5];

Using combos

A more advanced feature of JFormPane are the use of combos as a datatype. Combos allow the user to select an item from a multiple option combo box. The next image illustrates this:


In order to add a combo field to our form we must create an array with the options the user can choose from, and add the options to the FormField, as follows:
String[] colors = {
	"Yellow",
	"Red",
	"Blue"
};

FormField colorField = new FormField("Favourite Color", FormField.Type.COMBOBOX);
colorField.setCombos(colors);

That's it, in order to be able to use JFormPane, you will have to download the melqOS jar (v. 0.95 or higher) available at http://sourceforge.net/projects/melq/, and its dependencies (JCalendar and JSqlParser).
API documentation can be found at http://melq.sourceforge.net/api/.

Feel free to post any comments!

No comments:

Post a Comment