Row Table Model
Posted by Rob Camick on November 21, 2008
The DefaultTableModel is a good general purpose model that allows great flexibility. It provides dynamic functionality when dealing with rows and columns. However, it has been my experience that most applications tend to deal with rows of data and dynamic rows more than column data and dynamic columns. So maybe if we remove the column functionality and improve the row functionality we can create a better general purpose table model.
The RowTableModel was designed to replace the AbstractTableModel as the base table model for tables that need to access data as rows of data. It will provide the storage for the data as well as the methods to access the data. It will also provide some convenience methods to make customizing the model easier.
The main functionality added is the ability to deal with rows of data easier. You don’t lose the cell related functionality, you just gain row level features. The row related methods are as follows:
- addRow – convenience method that invokes insertRow to add a row Object to the end of the model
- getRow – return the row Object at the specified row
- getRowsAsArray – return the specified rows in an Array of the proper type
- getRowsAsList – return the specified rows in a List of the proper type
- insertRow – insert a row Object at the specified row in the model
- insertRows – insert a List of row Objects at the specified row in the model
- moveRow – move a range of row Objects to the specified location in the model
- removeRowRange – remove a range of row Objects from the model
- removeRows – remove 1 or more row Objects from the model
- replaceRow – update the row with a new row Object
Now that we no longer need to worry about dynamic changes to the columns, we can add a few convenience methods to the model that will allow us to easily customize the behavour of the model.
- setColumnClass – specify the class of individual columns
- setModelEditable – specify editable property for the entire model.
- setColumnEditable – specify editable property at a column level. This property will have preference over the model editable property.
The RowTableModel is an abstract class. It does not implement the getValueAt() or setValueAt() methods of the TableModel. This will allow you to extend the model to support row Objects of any type in the model. You will need to extend this class to implement these methods for your particular row Object type. For a simple example of how this might be done see the JButtonTableModel example code found below.
In my next couple of entries I will provide two concrete implementations. First, for rows of Lists, which can be used to replace the DefaultTableModel. The other will be a generic implementation for any bean Object.
Of course feel free to provide your own custom implementation for any of your classes. A custom implementation will always be more efficient than the generic implementations suggested above.