我知道要删除一行我应该这样做:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToTable);
model.removeBook(rowToModel);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
但是,现在我尝试使用没有rowToModel
变量的方法并且仍然正确删除:
if (table.getSelectedRow() > -1) {
int rowToTable = table.getSelectedRow();
model.removeBook(rowToTable);
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
我的removeBook()
方法:
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();
}
}
为什么这两个都有效?! 哪个是正确的?
答案 0 :(得分:4)
只有在表既没有排序也没有过滤时,它无需转换即可工作 - 因为您的代码无法知道它是否存在,它必须始终转换行索引。 BTW,列索引相同,因为用户可能已经移动了列