Author: Zafir Anjum
Note that if you are using your own subclass of AbstractTableModel(), this doesn't apply to you. Your TableModel should provide such a feature.
The following code is for those who let JTable create the TableModel. If you don't know what a table model is, don't worry. Just use the code below.
static public void deleteAllData( JTable table )
{
if( table.getModel() instanceof DefaultTableModel )
{
((DefaultTableModel)table.getModel()).setNumRows(0);
}
else
{
int cols = table.getModel().getColumnCount();
table.setModel( new DefaultTableModel(0, cols) );
}
}
The code above preserse the number of columns but does not preserve any of the rows. The result is a table with zero rows but the same number of columns as earlier.
In the code above, we make a check whether the table model is an instance of a DefaultTableModel. This is required because when you create JTable giving it initial data, Swing creates an anonymous subclass of AbstractTableModel.
Posted On: 9-Jan-1999