Monday, October 27, 2008

How to Bind Map with Jgoodies binding framework

Hi All,

Good news! now we can bind the map/hashmap to the jgoodies binding framework.

I was working on it since yesterday and after understanding the concept of jgoodies binding structure, I did my RnD which was successful. Now, the swing binding has no limits .... we are no more slaves of POJOs :) hehehe.

Lets come to the point and I will explain you with my code. It is a simple code but makes the difference.


/**
* This is the Map Based Value model which will replace the Bean's ValueModel given my JGoodies
* By using this model we can avoid the usage of many different kind of domain object instead just use Map/HashMap
* which will hold the key-value. It will help us to standardizing the UI
* @author Anees
*
*/
public class MapValueModel extends AbstractValueModel {

private static final long serialVersionUID = 1L;

protected Map map;
protected Object key;

/**
*
* @param map
* @param key
*/
public MapValueModel(Map map, Object key){
this.key = key;
this.map = map;
}

/**
*
*/
public MapValueModel(){}

/**
*
* @return
*/
public Object getKey() {
return key;
}
/**
*
* @param key
*/
public void setKey(Object key) {
Object oldKey = this.key;
this.key = key;
firePropertyChange("key", oldKey, key);
}

/**
* Retrieve the value.
*
* @return the value.
*/
public Object getValue(){
return map.get(key);
}

/**
* Set the value.
*
* @param newValue the new value.
*/
public void setValue(Object newValue){
Object oldValue = map.get(key);
map.put(key, newValue);
fireValueChange(oldValue, newValue);
}

/**
*
* @param map
*/
public void setMap(Map map){
Map oldMap = this.map;
Object oldValue = oldMap.get(key);
this.map = map;
firePropertyChange("map", oldMap, map);
fireValueChange(oldValue, getValue());
}
}



In this ValueModel, we also don't need to add firePropertyChange to any domain object and makes the life easy.

Now its usage with a simple example.


/**
* @author Anees
*
*/
public class TestingMapBinding {

/**
* @param args
*/
public static void main(String[] args) {

Map map = new HashMap();
map.put("firstName", "Anees");

MapValueModel mapValueModel = new MapValueModel(map,"firstName");

JTextField firstNameField = new JTextField();
Bindings.bind(firstNameField, mapValueModel);

JPanel panel = new JPanel();
panel.add(firstNameField);

JFrame frame = new JFrame("Testing Map Bindings...");
frame.getContentPane().add(panel);

frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.show();
frame.pack();

}

}



Try this code and see how beautifully we can extend the Jgoodies binding framework to work with any kind of object whether it is Bean (POJOs) or key-value pair romance.

Cheers and enjoy JGoodies

No comments: