Delete all rows from a Java JTable with a custom TableModel

I want to clear all rows in a custom TableModel. Unfortunately, a custom TableModel in Java does not allow use of most efficient of row clearing methods, which only applies to a DefaultTableModel like that shown below:
myTableModel.getDataVector().removeAllElements();
myTableModel.fireTableDataChanged();

To do an all clear like the above, for a custom TableModel, you need to reset the TableModel like that shown below:
myTableModel = new MyTableModel();
myTable.setModel(myTableModel);

If there are no rows in the custom TableModel, it throws an Array out of bounds exception

try {
   myTableModel = new MyTableModel();
   myTable.setModel(myTableModel);
} catch (Exception ex) {
   System.err.println(ex.getMessage());
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s