Delete a selected row in JTable with a custom model

DefaultTableModel model = (DefaultTableModel) myTable.getModel(); //Get reference to model
model.removeRow(x);                                               //Remove row x

You can also add a method deleteRow(int row) to your custom model class code as in:

public class MyTableModel extends AbstractModel {
   private Vector dataVector = new Vector();
   String[] columnNames = {"First Name", "Last Name", "Age"};
   public int getRowCount() {
      if (dataVector.size() <= 0) 
      {
         return 0;
      } else {
          return dataVector.size();
      }
   }

   public void deleteRow(int row) {
      if (dataVector.size()  0) {
         dataVector.remove(row);            //removes a row based on number from the data
         fireTableRowsDeleted(row, row);    //updates the table
      }
   }
}

Then in the GUI code, do this to call above deleteRow method:
myTableModel.deleteRow(myTable.getSelectedRow());

You can also delete a range of rows using:

DefaultTableModel model = jTable.getModel();
int numRows = jTable.getSelectedRows().length;
for(int i=0; i< numRows; i++ )
   model.removeRow(jTable.getSelectedRow());

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