it works without conversion only if the table is neither sorted nor filtered - as your code can't know whether it is, it must convert the row index always. BTW, same for column index, as the user might have moved the column
Remove JTable row without convert RowIndex To Model
-
29-06-2022 - |
Question
I know that for remove a row i should do this:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToTable);
model.removeBook(rowToModel);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
But, Now i try this method without rowToModel
variable and still remove correctly:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
model.removeBook(rowToTable);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
My removeBook()
method:
public void removeBook(int row) {
Connection connection;
PreparedStatement preparedStatement;
String query = "Delete from BookTable where id=?";
try {
connection = DriverManager.getConnection(...);
Object id = this.getValueAt(row, 0);
preparedStatement = connection.prepareStatement(query);
preparedStatement.setObject(1, id);
if (preparedStatement.executeUpdate() == 1) {
this.removeRow(row);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
Why both of this works?! And which is correct?
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow