Reputation: 180
here's my ui:
As I soon as uncheck the checkbox "single" the following rows in the table which has room type as "Single" needs to be removed.
here's how I attempted:
private void singlecheckboxActionPerformed(java.awt.event.ActionEvent evt) {
if (!singlecheckbox.isSelected()) {
for (int i = 0; i <roomtable.getRowCount(); i++) {
if (((DefaultTableModel)roomtable.getModel()).getValueAt(i, 1).equals("Single")) {
((DefaultTableModel) roomtable.getModel()).removeRow(i);
}
}
}
}
But the issue is only the first row is removed, not first and the second..
Upvotes: 1
Views: 65
Reputation: 347184
Once the first row is removed, the rowCount
changes...
For example, this is what's going on your loop
i = 0
rowCount = 2
delete Row at i
rowCount = 1;
i = 1 ... 1 > rowCount, exit...
Instead you could try something more like...
((DefaultTableModel) roomtable.getModel()).setRowCount(0);
I know, massive cheat...
For future reference, when deleting this from some kind list (and there's no removeAll
or clear
method), it might be better to use something more like...
while (count > 0) {
remove first element from list...
}
Updated...
Okay, so you need to remove "certain" items...you can use a for-loop
as the automatically changes the index value, you need more control over the index value and increment only when you need it to change, like when you want to keep the row, for example...
DefaultTableModel model = (DefaultTableModel)roomtable.getModel();
int row = 0;
while (row < model.getRowCount()) {
if ((model).getValueAt(row, 1).equals("Single")) {
model.removeRow(row);
} else {
row++;
}
}
Upvotes: 3