So I’m using this for loop to go through the values held in the first column. Then the if statement deletes the row if the value entered by the user is equal to the the value held in String hold. I am able to delete the first row but can not delete any row after that. What am I doing wrong?
private void addButtonActionPerformed(java.awt.event.ActionEvent evt) { //adds a row to table String name = JOptionPane.showInputDialog("Enter"); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); model.addRow(new Object[]{name, "JohnSMith@example.com", "03-16/05-17"}); } private void deleteButtonActionPerformed(java.awt.event.ActionEvent evt) { // deletes row from table String dName = JOptionPane.showInputDialog("Enter"); DefaultTableModel model = (DefaultTableModel) jTable1.getModel(); int rows = jTable1.getRowCount(); for(int i = 0; i <= rows;i++){ String hold = jTable1.getValueAt(i, 0).toString(); if(hold.equals(dName)){ model.removeRow(i); } break; } }
Advertisement
Answer
Problems in your code:
You have a
break;
in your for loop that is probably misplaced. Did you intend that to be part of theif(hold.equals(name)){}
block?You are deleting rows from the model using a view index.
JTable.getRowCount
returns the number of rows in the view, not the model. The number of rows in the view can differ from the number of rows in the model due to filtering.You then iterate the rows using an index, look up values in the view to then delete from the model. That will fail when you have sorting in your JTable.
You need to convert view indices to model indices and vice versa using the
JTable.convertRowIndexToView
andJTable.convertRowIndexToModel
.Same deal for columns, columns can be rearranged by the user by dragging them to a different position. The call to
jTable1.getValueAt(i, 0)
will give you the value in the first column in the view, not the model. Look intoJTable.convertColumnIndexToView
andJTable.convertColumnIndexToModel
.As these rows are deleted, the number of rows in the model changes of course, so the check with
i<rows
will lead to array out of index exceptions.
Two alternative ways to delete matching rows (in order of my preference):
Loop the model with a
for(int i=0;i!=model.getRowCount();++i)
. Look up the value usingmodel.getValueAt()
. Delete the row withmodel.removeRow()
, afterwards decrement your loop variable (egmodel.removeRow(i--);
).Iterate the model’s
dataVector
to find the rows to delete, and delete them usingIterator.remove
. After your loop, callfireTableChanged
on your model.