Monday, October 27, 2008

JTable binding with Map based ValueModel

Hi All,

Today, I will show you how we can bind JTable with Map based ValueModel. Please see the following example which will explain you how easy and flexible it is to use this concept.

You have to extends the AbstractTableAdapter as explained below.

/**
* @author Anees
*
*/
public class MapTableAdapter extends AbstractTableAdapter {

private static final long serialVersionUID = 1L;

private String[] columnNames;

public MapTableAdapter (ListModel listModel, String[] columnNames) {
super(listModel, columnNames);
this.columnNames = columnNames;
}

public Object getValueAt(int rowIndex, int columnIndex) {
Map dataMap = (Map) getRow(rowIndex);
String name = columnNames[columnIndex];
Object value = null;
if(dataMap.containsKey(name)){
value = dataMap.get(name);
}
return value;
}

}

the following line of code gives you the real example how to use this AbstractTableAdapter.

List mapValueList = new ArrayList();

ArrayListModel arrayListModel = new ArrayListModel();
Iterator iterator= rowDataMap.keySet().iterator();
while(iterator.hasNext()){
Integer rowIndex = iterator.next();
Map dataMap = rowDataMap.get(rowIndex);
arrayListModel.add(dataMap);
}


SelectionInList selectionInList = new SelectionInList((ListModel) arrayListModel);

String namesArray[] =(String[]) namesList.toArray(new String[namesList.size()]);

ViewArchiveTableAdapter viewArchiveTableAdapter =
new ViewArchiveTableAdapter(selectionInList, namesArray);

JTable table = new JTable(viewArchiveTableAdapter);

table.setSelectionModel(new SingleListSelectionAdapter(
selectionInList.getSelectionIndexHolder()));
JScrollPane scrollPane = new JScrollPane(table);
scrollPane.setPreferredSize(table.getPreferredSize());
scrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS);

Hopefully, you all will be able to understand this concept and feel very comfortable to use the Map based binding rather than POJO (Bean) based binding.

Cheers and enjoy the creativity and innovation.

No comments: