Monday, April 13, 2009

Use of Nebula CompositeTable and Databinding

I recently wrote a snippet illustrating how to use the nebula compositetable widget in conjunction with jface databinding.

Whenever we want to use compositetable with databinding, we must face two difficulties :

  • We have to bind the numRowsInCollection property of compositetable to the size the the collection in our model (in my snippet heroesListSize);

  • Since compositetable has its own pool of row object, each row will be used several times for several different data. So we have to unbind each row object prior to bind new data (in my snippet, I do that in my IRowContentProvider implementation);


If you manage correctly theses two difficulties, the use of databinding with compositetable is really easy.

Here is the code of my snippet :

/*******************************************************************************
* Copyright (c) 2000, 2004 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.nebula.snippets;

/*
* Text example snippet: verify input (only allow digits)
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import java.beans.PropertyChangeListener;
import java.beans.PropertyChangeSupport;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.BeansObservables;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.dialogs.TitleAreaDialog;
import org.eclipse.jface.layout.GridLayoutFactory;
import org.eclipse.jface.window.Window;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.DisposeEvent;
import org.eclipse.swt.events.DisposeListener;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.nebula.widgets.compositetable.CompositeTable;
import org.eclipse.swt.nebula.widgets.compositetable.IRowContentProvider;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class SnippetCompositeTableDataBinding {

/**
* A Model class representing a hero
*
* @author sylvere richard
*
*/
private static class Hero {
private String name;

private String firstname;

public Hero() {
}

/**
* copy constructor
* @param hero
*/
public Hero(Hero hero) {
this.firstname = hero.firstname;
this.name = hero.name;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getFirstname() {
return firstname;
}

public void setFirstname(String firstname) {
this.firstname = firstname;
}

}

/**
* A model class containing a list of persons.
*
* @author sylvere richard
*
*/
private static class MyModel {
private final PropertyChangeSupport support = new PropertyChangeSupport(
this);

/**
* @param listener
*/
public void addPropertyChangeListener(PropertyChangeListener listener) {
support.addPropertyChangeListener(listener);
}

/**
* @param propertyName
* @param listener
*/
public void addPropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
support.addPropertyChangeListener(propertyName, listener);
}

/**
* @param listener
*/
public void removePropertyChangeListener(PropertyChangeListener listener) {
support.removePropertyChangeListener(listener);
}

/**
* @param propertyName
* @param listener
*/
public void removePropertyChangeListener(String propertyName,
PropertyChangeListener listener) {
support.removePropertyChangeListener(propertyName, listener);
}

/**
*
* @param propertyName
* @param oldValue
* @param newValue
*/
protected void firePropertyChange(String propertyName, Object oldValue,
Object newValue) {
support.firePropertyChange(propertyName, oldValue, newValue);
}

private final List heroes = new LinkedList();

public List getHeroes() {
return heroes;
}

/**
* Returns how many heroes the model contains.
*
* @return
*/
public int getHeroesListSize() {
return getHeroes().size();
}

/**
* Adds a new hero to the list of people
*
* @param p
*/
public void addHero(Hero p) {
getHeroes().add(p);
// notify whenever the hero list size changes
support.firePropertyChange("heroesListSize",
getHeroesListSize() - 1, getHeroesListSize());
}

public void removePerson(Hero person) {
getHeroes().remove(person);
// notify whenever the hero list size changes
support.firePropertyChange("heroesListSize",
getHeroesListSize() + 1, getHeroesListSize());
}
}

/**
* contains size of table columns
*/
private static int[] cols = new int[] { 0, 30, 60, 75 };

/**
* Header of my table
*
* @author sylvere richard
*
*/
private static class Header extends Composite {
public Header(Composite parent, int style) {
super(parent, style);

doLayout();
}

private void doLayout() {
setLayout(new FormLayout());
Label lblName = new Label(this, SWT.CENTER);
lblName.setText("Name");

int index = 0;
FormData data = new FormData();
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
data.top = new FormAttachment(0, 100, 5);

lblName.setLayoutData(data);
index++;

Label lblFirstname = new Label(this, SWT.CENTER);
lblFirstname.setText("Firstname");

data = new FormData();
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
data.top = new FormAttachment(0, 100, 5);

lblFirstname.setLayoutData(data);
index++;

Label lblAction = new Label(this, SWT.CENTER);
lblAction.setText("Action");

data = new FormData();
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
data.top = new FormAttachment(0, 100, 5);

lblAction.setLayoutData(data);

}
}

/**
* A row of my table
*
* @author sylvere richard
*
*/
private static class Row extends Composite {

private DataBindingContext dbcRow;

private Text lastname;

private Text firstname;

private Button action;

public Row(Composite parent, int style) {
super(parent, style);
doLayout();

addDisposeListener(new DisposeListener() {
@Override
public void widgetDisposed(DisposeEvent e) {
// in case the row is bound, we unbind it
unbind();
}
});
}

private void doLayout() {
lastname = new Text(this, SWT.BORDER);
firstname = new Text(this, SWT.BORDER);
action = new Button(this, SWT.NONE);
action.setText("Delete");

setLayout(new FormLayout());

// column index
int index = 0;
FormData data = new FormData();
data.top = new FormAttachment(0, 100, 5);
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
lastname.setLayoutData(data);
index++;

data = new FormData();
data.top = new FormAttachment(0, 100, 5);
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
firstname.setLayoutData(data);
index++;

data = new FormData();
data.top = new FormAttachment(0, 100, 5);
data.left = new FormAttachment(cols[index], 100, 5);
data.right = new FormAttachment(cols[index + 1], 100, 0);
action.setLayoutData(data);
index++;
}

/**
* Unbind the current row. Be sure to call this method before any call
* to bind.
*/
public void unbind() {
if (dbcRow != null) {
dbcRow.dispose();
dbcRow = null;
}
}

/**
* Binds the current ro with the given Person
*
* @param p
* The Person bean to bind.
*/
public void bind(Hero p) {
dbcRow = new DataBindingContext();

Binding b = dbcRow.bindValue(SWTObservables.observeText(lastname,
SWT.Modify), PojoObservables.observeValue(p, "name"), null,
null);

b = dbcRow.bindValue(SWTObservables.observeText(firstname,
SWT.Modify), PojoObservables.observeValue(p, "firstname"),
null, null);

}

}

/**
* A simple dialog to create a new person.
*
* @author sylvere richard
*
*/
private static final class PersonTitleAreaDialog extends TitleAreaDialog {
private Text txName;
private Text txFirstname;
private final Hero hero = new Hero();

private DataBindingContext dbc = new DataBindingContext();

private PersonTitleAreaDialog(Shell parentShell) {
super(parentShell);

}

@Override
protected Control createContents(Composite parent) {
Control ret = super.createContents(parent);
setTitle("Add new Hero");
setMessage("Enter here your favorite hero :");
return ret;
}

protected Control createDialogArea(Composite parent) {
Composite composite = (Composite) super.createDialogArea(parent);

Label lbName = new Label(composite, SWT.NONE);
lbName.setText("Name :");

txName = new Text(composite, SWT.BORDER);

Label lbFirstname = new Label(composite, SWT.NONE);
lbFirstname.setText("Firstname :");

txFirstname = new Text(composite, SWT.BORDER);

GridLayoutFactory.fillDefaults().generateLayout(composite);

// binding
Binding b = dbc.bindValue(SWTObservables.observeText(txFirstname,
SWT.FocusOut), PojoObservables.observeValue(hero,
"firstname"), null, null);

b = dbc.bindValue(SWTObservables.observeText(txName, SWT.FocusOut),
PojoObservables.observeValue(hero, "name"), null, null);

return composite;
}

@Override
public int open() {
return super.open();
}

@Override
public boolean close() {
dbc.dispose();
return super.close();
}

public Hero getHero() {
// returns a copy
return new Hero(hero);
}
}

/**
* This composite contains the CompositeTable and a button to add new rows
*
* @author sylvere richard
*
*/
private static class MainCompo extends Composite {

private CompositeTable table;
private Button addNew;
private final MyModel model = new MyModel();

private final DataBindingContext dbc = new DataBindingContext();

public MainCompo(Composite parent, int style) {
super(parent, style);

doLayout();
}

private void doLayout() {
setLayout(new FormLayout());

table = new CompositeTable(this, SWT.NULL);
table.setBackground(getDisplay().getSystemColor(
SWT.COLOR_WIDGET_BACKGROUND));
new Header(table, SWT.NULL);
new Row(table, SWT.NULL);

addNew = new Button(this, SWT.NONE);
addNew.setText("Add new Hero");
addNew.addSelectionListener(new SelectionAdapter() {

@Override
public void widgetSelected(SelectionEvent e) {
PersonTitleAreaDialog d = new PersonTitleAreaDialog(
getShell());
d.open();
final int result = d.getReturnCode();
if (result == Window.OK) {
Hero p = d.getHero();
getModel().addHero(p);
}
}
});

FormData data = new FormData();
data.left = new FormAttachment(0, 100, 5);
data.right = new FormAttachment(100, 100, -5);
data.top = new FormAttachment(0, 100, 5);
data.bottom = new FormAttachment(addNew, -5, SWT.TOP);
table.setLayoutData(data);
table.setRunTime(true);

data = new FormData();
data.right = new FormAttachment(100, 100, -5);
data.bottom = new FormAttachment(100, 100, -5);
addNew.setLayoutData(data);
}

/**
* In this method, we bind the heroes list size with the
* compositetable's property 'numRowsInCollection'.
*
*/
public void binding() {

// table.setNumRowsInCollection(model.getPeople().size());
Binding b = dbc.bindValue(PojoObservables.observeValue(table,
"numRowsInCollection"), BeansObservables.observeValue(
model, "heroesListSize"), new UpdateValueStrategy(
UpdateValueStrategy.POLICY_NEVER),
new UpdateValueStrategy());

table.addRowContentProvider(new IRowContentProvider() {

/**
* Keeps a reference of each delete listener for each row, so we can
* remove a listener when compositetable associate the row to another hero.
*/
private Map map = new HashMap();

/**
* * Since the compositetable has its own pool of Row elements,
* we must first ensure to unbind if necessary the row before
* rebinding it with the Hero given as parameter.
*
* In the same way, we remove and add selectionlistener.
*/
public void refresh(CompositeTable sender,
int currentObjectOffset, Control rowControl) {
Row row = (Row) rowControl;
final Hero p = model.getHeroes().get(currentObjectOffset);

// unbind previous hero
row.unbind();

// remove previous listener if nay
if (map.get(row) != null) {
row.action.removeSelectionListener(map.get(row));
}

//bind the new hero
row.bind(p);

// add selectionlistener
SelectionListener listen = new SelectionAdapter() {
@Override
public void widgetSelected(SelectionEvent e) {
getModel().removePerson(p);
}
};
row.action.addSelectionListener(listen);
// keep a reference to this listener to be able to remove it
//during the next refresh
map.put(row, listen);
}
});
}

public MyModel getModel() {
return model;
}
}

/**
* Main entry point.
* @param args
*/
public static void main(String[] args) {
final Display display = new Display();

Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
public void run() {
Shell shell = new Shell(display);
shell.setText("Jules Verne's Heroes");
shell.setBounds(0, 0, 400, 200);
shell.setLayout(new FormLayout());

// creation of the composite containing the table
MainCompo compo = new MainCompo(shell, SWT.NONE);

// position it on the shell
FormData data = new FormData();
data.left = new FormAttachment(0, 100, 5);
data.right = new FormAttachment(100, 100, -5);
data.top = new FormAttachment(0, 100, 5);
data.bottom = new FormAttachment(100, 100, -5);
compo.setLayoutData(data);

// add some data to the model
populateModel(compo.getModel());

// binding the UI with the model
compo.binding();

// start the UI
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
});
display.dispose();
}

/**
* populates the given model with some data
*
* @param md
*/
private static void populateModel(MyModel md) {
Hero p = new Hero();
p.setName("Fogg");
p.setFirstname("Phileas");
md.getHeroes().add(p);

p = new Hero();
p.setName("Aronnax");
p.setFirstname("Pierre");
md.getHeroes().add(p);

p = new Hero();
p.setName("Strogoff");
p.setFirstname("Michel");
md.getHeroes().add(p);

p = new Hero();
p.setName("Nemo");
p.setFirstname("Captain");
md.getHeroes().add(p);

p = new Hero();
p.setName("Barbicane");
p.setFirstname("Impey");
md.getHeroes().add(p);
}
}



Any comment or suggestion is welcomed !!

Bye !!

Sunday, April 12, 2009

JFace databinding : implementing roundtrip

As developers, we are sometimes (often?) confronted with annoying user demands.

For example, last week, I implemented a classic form enabling the user to enter financial data. I used a ControlDecoration for each field to indicate as precisely as possible errors or warnings to application's users.

I was pretty happy with the result and proud to present it to my customer. Then comes the disillusion....

He asks me to change the behavior of each field validation. When user fills a field with bad data, we must not display a small icon indicating that the data are wrong, we must instead replace the content of the field with the last known valid data...

After googling on this demand, I finally found a bug report 238222 on the eclipse bug database that could help me implementing this functionnality.

Unfortunately, the workaround proposed doesn't work properly.

So I give here my own solution. The main element is my ValidatorRoundtrip class.

It implements IValidator so I can use it with any Validator points availbale in UpdateValueStrategy.

Basically, this class, calls IStatus doValidation(String value), check for the IStatus returned by this call :
- if the IStatus is an error or a cancel, the view is updated to reflect the model (that contains the old valid value)
- if the IStatus is an ok or warning or info IStatus, the normal flow is executed and the modle is updated with the new value.

Here is the code of ValidationRoundtrip :

import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.validation.IValidator;
import org.eclipse.core.runtime.IStatus;

/**
*
* @author sylvere richard
*
*/
public abstract class ValidatorRoundtrip implements IValidator {

private final Binding b;
private final Realm realm;

public ValidatorRoundtrip(Realm realm, Binding b) {
this.realm = realm;
this.b = b;
}

/**
* Method declared final. Validation logic must be put in method
* ValidatorRoundtrip.doValidation
*
*
* Will call doValidation.
*
* If the IStatus returned by doValidation is an error
* or a cancel, it will force a refresh of the target by calling updateModelToTarget()
* to restore the previous value on screen.
* Otherwise, the process flow is unchanged.
*/
@Override
public final IStatus validate(Object value) {
final IStatus res = doValidation(value);
if (res.matches(IStatus.INFO | IStatus.WARNING) || res.isOK()) {
return res;
}

realm.asyncExec(new Runnable() {

@Override
public void run() {
b.updateModelToTarget();
}
});
return res;
}

/**
* Puts validation logic here
* @param value
* @return
*/
public abstract IStatus doValidation(Object value);
}



So to use this class, we just have to put our business log in the doValidation method.

Here is a snippet using demonstrating the use of this class :

/*
* Snippet demonstrating the use of ValidatorRoundtrip.
* A ValidatorRoundtrip is used to restore the last valid
* value on screen after a validation error occurs.
*
* For a list of all SWT example snippets see
* http://www.eclipse.org/swt/snippets/
*/
import org.eclipse.core.databinding.Binding;
import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.UpdateValueStrategy;
import org.eclipse.core.databinding.beans.PojoObservables;
import org.eclipse.core.databinding.observable.Realm;
import org.eclipse.core.databinding.validation.ValidationStatus;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.jface.databinding.swt.SWTObservables;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.resource.JFaceResources;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

public class SnippetRoundtrip {

/**
* the model bound to the UI.
*
*/
private static class MyModel {

private String myText;

public String getMyText() {
return myText;
}

public void setMyText(String myText) {
this.myText = myText;
}
}

/**
*
* A composite that will contains a text to validate.
*
*/
private static class MainCompo extends Composite {
private final MyModel model = new MyModel();

private Text text;
private ControlDecoration ctrlDeco;

private Button button;

/**
*
* @param parent
* @param style
*/
public MainCompo(Composite parent, int style) {
super(parent, style);
doLayout();
}

private void doLayout() {
setLayout(new FormLayout());

Label lbl = new Label(this, SWT.NONE);
lbl.setText("Enter a text without 'aa' :");

text = new Text(this, SWT.BORDER);

ctrlDeco = new ControlDecoration(text, SWT.TOP | SWT.LEFT);
ctrlDeco.hide();
ctrlDeco.setImage(JFaceResources
.getImage(Dialog.DLG_IMG_MESSAGE_WARNING));

button = new Button(this, SWT.NONE);
button.setText("Hello");

FormData data = new FormData();
data.left = new FormAttachment(0, 100, 5);
data.top = new FormAttachment(text, 0, SWT.CENTER);
lbl.setLayoutData(data);

data = new FormData();
data.left = new FormAttachment(lbl, 5+ctrlDeco.getImage().getBounds().width, SWT.RIGHT);
data.top = new FormAttachment(0, 100, 5);
data.right = new FormAttachment(100,100,-5);
text.setLayoutData(data);

data = new FormData();
data.left = new FormAttachment(lbl, 5, SWT.RIGHT);
data.top = new FormAttachment(text,5);
button.setLayoutData(data);

}

/**
* we bind text to MyModel.myText
*/
public void binding(final DataBindingContext dbc) {
// let's go binding text to MyModel.myText
// we will do validation
// In case the string typed by the user contains 'aa', we do the roundtrip to go
// back to the last correct value.
// A sequence like 'bb' is allowed but leads to a warning displayed
// to the user.

UpdateValueStrategy strgTargetToModel = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
UpdateValueStrategy strgModelToTarget = new UpdateValueStrategy(
UpdateValueStrategy.POLICY_UPDATE);
Binding b = dbc.bindValue(SWTObservables.observeText(text,
SWT.FocusOut), PojoObservables.observeValue(model, "myText"),
strgTargetToModel, strgModelToTarget);

strgTargetToModel.setAfterGetValidator(new ValidatorRoundtrip(dbc
.getValidationRealm(), b) {
@Override
public IStatus doValidation(Object value) {
if (value == null) {
ctrlDeco.hide();
return ValidationStatus.ok();
}
String strVal = (String) value;
//error, contains 'aa'
if (strVal.indexOf("aa") != -1) {
return ValidationStatus
.error("the value of this text must NOT contains 'aa'!!");
}
//warning, contains 'bb'
if (strVal.indexOf("bb") != -1) {
ctrlDeco.show();
ctrlDeco.setDescriptionText("be careful, the value of this text contains 'bb' !!");
return ValidationStatus
.warning(ctrlDeco.getDescriptionText());
}
ctrlDeco.hide();
return ValidationStatus.ok();
}
});

}

}

/**
* Main entry point
* @param args
*/
public static void main(String[] args) {
final Display display = new Display();

Realm.runWithDefault(SWTObservables.getRealm(display), new Runnable() {
public void run() {
Shell shell = new Shell(display);
shell.setBounds(0,0,400,200);
shell.setLayout(new FormLayout());
MainCompo compo = new MainCompo(shell, SWT.NONE);
FormData data = new FormData();
data.left = new FormAttachment(0, 100,0);
data.right = new FormAttachment(100, 100,0);
data.top = new FormAttachment(0, 100,0);
data.bottom = new FormAttachment(100, 100,0);
compo.setLayoutData(data);

final DataBindingContext dbc = new DataBindingContext();
compo.binding(dbc);
shell.open();

while (!shell.isDisposed()) {
if (!display.readAndDispatch())
display.sleep();
}
}
});
display.dispose();
}
}



Here is the list of jar we have to put in the classpath for this snippet to work :

com.ibm.icu_3.8.1.v20080530.jar
org.eclipse.core.commands_3.4.0.I20080509-2000.jar
org.eclipse.core.databinding_1.1.1.M20080827-0800b.jar
org.eclipse.core.databinding.beans_1.1.1.M20080827-0800a.jar
org.eclipse.core.databinding.source_1.1.1.M20080827-0800b.jar
org.eclipse.core.runtime_3.4.0.v20080512.jar
org.eclipse.equinox.common_3.4.0.v20080421-2006.jar
org.eclipse.jface_3.4.2.M20090107-0800.jar
org.eclipse.jface.databinding_1.2.1.M20080827-0800a.jar
org.eclipse.osgi_3.4.3.R34x_v20081215-1030.jar
org.eclipse.swt_3.4.2.v3452b.jar
org.eclipse.swt.win32.win32.x86_3.4.1.v3452b.jar


Bye !

Sunday, September 28, 2008

SWT and FormData

I really hate to stupidly waste time when I code. And today, I spend more than one hour to find a stupid bug in my SWT program. I worked on a simple widget using FormLayout but it desperatly refused to display itself correctly. Let's consider the following snippet :


Label myLabel = ...;
Text myText = ...;

FormData data = null;
//error, don't do this !!!
data.left = new FormAttachment(myLabel, SWT.RIGHT, 5);
data.top = new FormAttachment(myLabel, SWT.CENTER, 0);
myText.setLayoutData(data);

You see the mistake ? Yes, you got it ! The constructor of FormAttachment is :


public FormAttachment(Control control, int offset, int alignment)


So I just have to invert offset and alignment to solve my problem. Here is the correct snippet :

Label myLabel = ...;
Text myText = ...;

FormData data = null;
//this time, it's ok
data.left = new FormAttachment(myLabel, 5, SWT.RIGHT);
data.top = new FormAttachment(myLabel, 0, SWT.CENTER);
myText.setLayoutData(data);


Yesterday, I read the excellent book of Joshua Bloch "Effective Java 2nd Ed.". This book explains how to take the most of the java language in 78 independent items. It's undoubtly a must-have for each java programmer.

Specifically, I read the item 2 :"Consider a builder when faced with many constructor parameters". And I thought I could have avoid this stupid bug if only FormData had its own builder class.

So I decided to write this builder class and I'm glad to publish this class in my blog:


import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.widgets.Control;

/**
* Class FormDataBuilder
*
* Utility class used to avoid the verbosity/opacity of FormData
* and FormAttachment.
* See the example below for how to use it :
* <pre>
FormData data = new FormDataBuilder()
.topAt(10)
.leftAlignedToTheRightOf(myControl, offset)
.build();
</pre>
gives the sam result as:
<pre>
FormData data = new FormData();
data.top = new FormAttachment(10, 100, 0);
data.left = new FormAttachment(myControl, offset, SWT.RIGHT);
</pre>
*
* THIS CLASS IS NOT THREAD-SAFE.
*
* @author Sylvere Richard
*
*/
public class FormDataBuilder {

private final static int denominator = 100;

private int top = Integer.MIN_VALUE;
private int insetTop = Integer.MIN_VALUE;

private int bottom = Integer.MIN_VALUE;
private int insetBottom = Integer.MIN_VALUE;

private int left = Integer.MIN_VALUE;
private int insetLeft = Integer.MIN_VALUE;

private int right = Integer.MIN_VALUE;
private int insetRight = Integer.MIN_VALUE;

private int width = Integer.MIN_VALUE;
private int height = Integer.MIN_VALUE;

private Control rightAlignedToTheRightOf = null;
private Control rightAlignedToTheLeftOf = null;
private Control rightAlignedToTheCenterOf = null;

private Control leftAlignedToTheRightOf = null;
private Control leftAlignedToTheLeftOf = null;
private Control leftAlignedToTheCenterOf = null;

private Control topAlignedToTheTopOf = null;
private Control topAlignedToTheBottomOf = null;
private Control topAlignedToTheCenterOf = null;

private Control bottomAlignedToTheTopOf = null;
private Control bottomAlignedToTheBottomOf = null;
private Control bottomAlignedToTheCenterOf = null;

private int rightAlignedToTheRightOfInset = Integer.MIN_VALUE;
private int rightAlignedToTheLeftOfInset = Integer.MIN_VALUE;
private int rightAlignedToTheCenterOfInset = Integer.MIN_VALUE;

private int leftAlignedToTheRightOfInset = Integer.MIN_VALUE;
private int leftAlignedToTheLeftOfInset = Integer.MIN_VALUE;
private int leftAlignedToTheCenterOfInset = Integer.MIN_VALUE;

private int topAlignedToTheTopOfInset = Integer.MIN_VALUE;
private int topAlignedToTheBottomOfInset = Integer.MIN_VALUE;
private int topAlignedToTheCenterOfInset = Integer.MIN_VALUE;

private int bottomAlignedToTheTopOfInset = Integer.MIN_VALUE;
private int bottomAlignedToTheBottomOfInset = Integer.MIN_VALUE;
private int bottomAlignedToTheCenterOfInset = Integer.MIN_VALUE;

/**
*
*/
public FormDataBuilder() {
}

/**
* Used to get a FormData properly configured by previous calls
* of all the methods beginning with top, bottom, left or right.
* Successive calls of build() produces different identical FormData object.
* @return Returns a FormData object.
*/
public FormData build() {
final FormData data = new FormData();

if (top != Integer.MIN_VALUE) {
data.top = new FormAttachment(top, denominator,
insetTop == Integer.MIN_VALUE ? 0 : insetTop);
}

if (bottom != Integer.MIN_VALUE) {
data.bottom = new FormAttachment(bottom, denominator,
insetBottom == Integer.MIN_VALUE ? 0 : insetBottom);
}

if (right != Integer.MIN_VALUE) {
data.right = new FormAttachment(right, denominator,
insetRight == Integer.MIN_VALUE ? 0 : insetRight);
}

if (left != Integer.MIN_VALUE) {
data.left = new FormAttachment(left, denominator,
insetLeft == Integer.MIN_VALUE ? 0 : insetLeft);
}

if (width != Integer.MIN_VALUE) {
data.width = width;
}

if (height != Integer.MIN_VALUE) {
data.height = height;
}

if (rightAlignedToTheRightOf != null) {
data.right = new FormAttachment(rightAlignedToTheRightOf,
rightAlignedToTheRightOfInset == Integer.MIN_VALUE ? 0
: rightAlignedToTheRightOfInset, SWT.RIGHT);
}
if (rightAlignedToTheLeftOf != null) {
data.right = new FormAttachment(rightAlignedToTheLeftOf,
rightAlignedToTheLeftOfInset == Integer.MIN_VALUE ? 0
: rightAlignedToTheLeftOfInset, SWT.LEFT);
}
if (rightAlignedToTheCenterOf != null) {
data.right = new FormAttachment(rightAlignedToTheCenterOf,
rightAlignedToTheCenterOfInset == Integer.MIN_VALUE ? 0
: rightAlignedToTheCenterOfInset, SWT.CENTER);
}

if (leftAlignedToTheRightOf != null) {
data.left = new FormAttachment(leftAlignedToTheRightOf,
leftAlignedToTheRightOfInset == Integer.MIN_VALUE ? 0
: leftAlignedToTheRightOfInset, SWT.RIGHT);
}
if (leftAlignedToTheLeftOf != null) {
data.left = new FormAttachment(leftAlignedToTheLeftOf,
leftAlignedToTheLeftOfInset == Integer.MIN_VALUE ? 0
: leftAlignedToTheLeftOfInset, SWT.LEFT);
}
if (leftAlignedToTheCenterOf != null) {
data.left = new FormAttachment(leftAlignedToTheCenterOf,
leftAlignedToTheCenterOfInset == Integer.MIN_VALUE ? 0
: leftAlignedToTheCenterOfInset, SWT.CENTER);
}

if (topAlignedToTheTopOf != null) {
data.top = new FormAttachment(topAlignedToTheTopOf,
topAlignedToTheTopOfInset == Integer.MIN_VALUE ? 0
: topAlignedToTheTopOfInset, SWT.RIGHT);
}
if (topAlignedToTheBottomOf != null) {
data.top = new FormAttachment(topAlignedToTheBottomOf,
topAlignedToTheBottomOfInset == Integer.MIN_VALUE ? 0
: topAlignedToTheBottomOfInset, SWT.LEFT);
}
if (topAlignedToTheCenterOf != null) {
data.top = new FormAttachment(topAlignedToTheCenterOf,
topAlignedToTheCenterOfInset == Integer.MIN_VALUE ? 0
: topAlignedToTheCenterOfInset, SWT.CENTER);
}

if (bottomAlignedToTheTopOf != null) {
data.bottom = new FormAttachment(bottomAlignedToTheTopOf,
bottomAlignedToTheTopOfInset == Integer.MIN_VALUE ? 0
: bottomAlignedToTheTopOfInset, SWT.RIGHT);
}
if (bottomAlignedToTheBottomOf != null) {
data.bottom = new FormAttachment(bottomAlignedToTheBottomOf,
bottomAlignedToTheBottomOfInset == Integer.MIN_VALUE ? 0
: bottomAlignedToTheBottomOfInset, SWT.LEFT);
}
if (bottomAlignedToTheCenterOf != null) {
data.bottom = new FormAttachment(bottomAlignedToTheCenterOf,
bottomAlignedToTheCenterOfInset == Integer.MIN_VALUE ? 0
: bottomAlignedToTheCenterOfInset, SWT.CENTER);
}

return data;
}

/**
* do the same as FormData data = ... data.top = new
* FormAttachment(numerator, 100, 0);
*
* @param numerator
* @return Returns this.
*/
public FormDataBuilder topAt(int numerator) {

return topAt(numerator, 0);
}

/**
* do the same as FormData data = ... data.top = new
* FormAttachment(numerator, 100, offset);
*
* @param numerator
* @param offset
* @return Returns this.
*/
public FormDataBuilder topAt(int numerator, int offset) {
this.top = numerator;
this.insetTop = offset;
return this;
}

/**
* do the same as FormData data = ... data.bottom = new
* FormAttachment(numerator, 100, 0);
*
* @param numerator
* @return Returns this.
*/
public FormDataBuilder bottomAt(int numerator) {

return bottomAt(numerator, 0);
}

/**
* do the same as FormData data = ... data.bottom = new
* FormAttachment(numerator, 100, offset);
*
* @param numerator
* @param offset
* @return Returns this.
*/
public FormDataBuilder bottomAt(int numerator, int offset) {
this.bottom = numerator;
this.insetBottom = offset;
return this;
}

/**
* do the same as FormData data = ... data.left = new
* FormAttachment(numerator, 100, 0);
*
* @param numerator
* @return Returns this.
*/
public FormDataBuilder leftAt(int numerator) {

return leftAt(numerator, 0);
}

/**
* do the same as FormData data = ... data.left = new
* FormAttachment(numerator, 100, offset);
*
* @param numerator
* @param offset
* @return Returns this.
*/
public FormDataBuilder leftAt(int numerator, int offset) {
this.left = numerator;
this.insetLeft = offset;
return this;
}

/**
* do the same as FormData data = ... data.right = new
* FormAttachment(numerator, 100, 0);
*
* @param numerator
* @return Returns this.
*/
public FormDataBuilder rightAt(int numerator) {

return rightAt(numerator, 0);
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(numerator, 100, offset);
*
* @param numerator
* @param offset
* @return Returns this.
*/
public FormDataBuilder rightAt(int numerator, int offset) {
this.right = numerator;
this.insetRight = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, 0, SWT.LEFT);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheLeftOf(Control ctr) {
return rightAlignedToTheLeftOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, offset, SWT.LEFT);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheLeftOf(Control ctr, int offset) {
this.rightAlignedToTheLeftOf = ctr;
this.rightAlignedToTheLeftOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, 0, SWT.CENTER);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheCenterOf(Control ctr) {
return rightAlignedToTheCenterOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, offset, SWT.CENTER);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheCenterOf(Control ctr, int offset) {
this.rightAlignedToTheCenterOf = ctr;
this.rightAlignedToTheCenterOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, 0, SWT.RIGHT);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheRightOf(Control ctr) {
return rightAlignedToTheRightOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.right = new FormAttachment(ctr, offset, SWT.RIGHT);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder rightAlignedToTheRightOf(Control ctr, int offset) {
this.rightAlignedToTheRightOf = ctr;
this.rightAlignedToTheRightOfInset = offset;
return this;
}

//LEFT
/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, 0, SWT.LEFT);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheLeftOf(Control ctr) {
return leftAlignedToTheLeftOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, offset, SWT.LEFT);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheLeftOf(Control ctr, int offset) {
this.leftAlignedToTheLeftOf = ctr;
this.leftAlignedToTheLeftOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, 0, SWT.CENTER);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheCenterOf(Control ctr) {
return leftAlignedToTheCenterOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, offset, SWT.CENTER);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheCenterOf(Control ctr, int offset) {
this.leftAlignedToTheCenterOf = ctr;
this.leftAlignedToTheCenterOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, 0, SWT.RIGHT);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheRightOf(Control ctr) {
return leftAlignedToTheRightOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.left = new FormAttachment(ctr, offset, SWT.RIGHT);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder leftAlignedToTheRightOf(Control ctr, int offset) {
this.leftAlignedToTheRightOf = ctr;
this.leftAlignedToTheRightOfInset = offset;
return this;
}

//TOP

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, 0, SWT.TOP);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheTopOf(Control ctr) {
return topAlignedToTheTopOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, offset, SWT.TOP);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheTopOf(Control ctr, int offset) {
this.topAlignedToTheTopOf = ctr;
this.topAlignedToTheTopOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, 0, SWT.CENTER);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheCenterOf(Control ctr) {
return topAlignedToTheCenterOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, offset, SWT.CENTER);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheCenterOf(Control ctr, int offset) {
this.topAlignedToTheCenterOf = ctr;
this.topAlignedToTheCenterOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, 0, SWT.BOTTOM);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheBottomOf(Control ctr) {
return topAlignedToTheBottomOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.top = new FormAttachment(ctr, offset, SWT.BOTTOM);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder topAlignedToTheBottomOf(Control ctr, int offset) {
this.topAlignedToTheBottomOf = ctr;
this.topAlignedToTheBottomOfInset = offset;
return this;
}

//BOTTOM

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, 0, SWT.TOP);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheTopOf(Control ctr) {
return bottomAlignedToTheTopOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, offset, SWT.TOP);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheTopOf(Control ctr, int offset) {
this.bottomAlignedToTheTopOf = ctr;
this.bottomAlignedToTheTopOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, 0, SWT.CENTER);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheCenterOf(Control ctr) {
return bottomAlignedToTheCenterOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, offset, SWT.CENTER);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheCenterOf(Control ctr, int offset) {
this.bottomAlignedToTheCenterOf = ctr;
this.bottomAlignedToTheCenterOfInset = offset;
return this;
}

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, 0, SWT.BOTTOM);
*
* @param ctr
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheBottomOf(Control ctr) {
return bottomAlignedToTheBottomOf(ctr, 0);
}

/**
* do the same as
* FormData data = ...
* data.bottom = new FormAttachment(ctr, offset, SWT.BOTTOM);
*
* @param ctr
* @param offset
* @return Returns this.
*/
public FormDataBuilder bottomAlignedToTheBottomOf(Control ctr, int offset) {
this.bottomAlignedToTheBottomOf = ctr;
this.bottomAlignedToTheBottomOfInset = offset;
return this;
}


}


Now, the simple snippet above can be (safely) written like this:


Label myLabel = ...;
Text myText = ...;

FormData data = null;
//the old version
//data.left = new FormAttachment(myLabel, 5, SWT.RIGHT);
//data.top = new FormAttachment(myLabel, 0, SWT.CENTER);

//here is the version using FormDataBuilder
data = new FormDataBuilder().leftAlignedToTheRightOf(myLabel, 5)
.topAlignedToTheCenterOf(myLabel);
myText.setLayoutData(data);


IMHO, the FormDataBuilder solution is less error-prone.

Thanks, M. Bloch !!!!