Search code examples
javadefaulttablemodel

DefaultTablemodel delete rows if the row has a specific value JAVA


I would like to delete rows if the first row String "Windows" but, it doesn't work well, it removes rows if the String value is "Windows" My code. Any help is going to be appreciated. :)

                                    for (int i = 0; i < model.getRowCount(); i++) {
                                        if ((String) model.getValueAt(i, 0) != "Windows") {
                                            model.removeRow(i);
                                        }
                                    }

Solution

  • To compare strings you can with equals directly

    Keep in mind that deleting a row reduces the size of your model, you could control subtracting the iterated for when you delete a row or not, not do all comparisons

    for (int i = 0; i < model.getRowCount(); i++) { 
       if (!model.getValueAt(i, 0).equals("Windows")){
    
       model.removeRow(i);
       i-=1;  // 
      }