Search code examples
javaswingjtabledefaulttablemodel

Removing multiple items from a Java JTable


So I have a default table model that is populated by an Object I created. One of the Objects is Name, with three other string properties of the object. I have a button that performs an action, now when this button performs this action I need to loop through all of the items in that DefaultTableModel and remove any and all items that have the same value in column 0 as the object chosen. So the problem I have is this will only remove one item with that value(Name). I need this code to remove all of the items that contain the same string value as column 0.

                int nRow = suggestedAcTableModel.getRowCount() - 1;

                for (int i = 0; i < nRow; i++) {

                    String acNameStr = suggestedAcTableModel.getValueAt(i, 0).toString();

                    if (acNameStr.equals(acName)) {

                        suggestedAcTableModel.removeRow(i);
                    }
                }

Solution

  • If you are wanting to search each column for the value and then delete the entire row if the value is found then see below.

    for (int i = 0; i < suggestedAcTableModel.getRowCount(); i++) {
        for(int j = 0; j < suggestedAcTableModel.getColumnCount(); j++){
            String acNameStr = suggestedAcTableModel.getValueAt(i, j).toString();
            if (acNameStr.equals(acName)) { 
               suggestedAcTableModel.removeRow(i);
               j = suggestedAcTableModel.getColumnCount();
               i--;
            }
        }
    }