Friday, December 5, 2008

Minimizing TableModel maintenance

Implementing TableModel in your Swing application is relatively simple. One of the straight-forward ways to do it was always to use switch statements to return or save data according to row/column number. And this is were the problem is. Every time you need to change default sequence of your columns you have to touch all methods with the switch statements.

The solution I came up with is very simple and is based on Java enums.

Define your columns as enum inside of your table model. This will be the default sequence of your columns. All you have to do now is to convert from column index to enum according to the sequence of enums. After that you can implement your switch statements using enums instead of column index. Going one step farther we can convert enum to column title. This brings us to an idea of class to support such table model implementation. I called it TableColumDefinitionSupport. Here it is.