If you always been using column numbers when implementing your TableModel, you’ll know that it a burden when you have to change the order of the columns.
If you normally do the following in your TableModel implementation:
@Override public String getColumnName(int column) {
switch(column) {
case 0: return "Closing Date";
case 1: return "Open Price";
case 2: return "Day High";
case 3: return "Day Low";
case 4: return "Close< Price";
}
return null;
}
You'll have to go through the source code and re-number each column whenever you need to change the order of the columns. There will be multiple places to update, such as the getColumnName and getValueAt methods. If you do complex rendering then you will also need to update the TableCellRenderer implementation as well.
To avoid hardcoding the column numbers, you can use enums. Enums are both more descriptive and have ordinal values.
The enum's ordinal value can substitute for the same purpose as the column number.
enum ColumnId {DATE, OPEN, HIGH, LOW, CLOSE};
@Override public String getColumnName(int column) {
return getColumnNameById(ColumnId.values()[column]);
}
public String getColumnNameById(ColumnId colId) {
switch(colId) {
case DATE: return "Closing Date";
case OPEN: return "Open Price";
case HIGH: return "Day High";
case LOW: return "Day Low";
case CLOSE: return "Close Price";
default: return colId.toString();
}
}
Below is the a full implementation of a TableModel using enums instead of hardcoding the column numbers.

Are you going to start practice using enums in your TableModel? Leave me a comment.
Related posts:
This is an excelent idea! I’ve always been trying to use constants instead hard coded numbers, but problems are the same. This is much more elegant solution. Remindes me of C/C++ best practices
.
I think it can be even more enhanced by defining enums with strings that are actually column names:
enum ColumnId{
DATE (“Date”),OPEN(“Open”)…. ;
String name;
public String getName(){ return name;}
}
Then you can just do:
public String getColumnNameById(Column id){
return id.getName();
}
This will work for a single language application. If your application support multiple languages, i.e. english, french, spanish, etc.., then you need to use Localization with ResourceBundles. You can use the enum as the key into the ResourceBundle in the getColumnName method.