1

我知道要删除一行我应该这样做:

        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();
    }
}

为什么这两个都有效?!哪个是正确的?

4

1 回答 1

4

只有当表格既没有排序也没有过滤时,它才可以在没有转换的情况下工作 - 因为您的代码无法知道它是否是,它必须始终转换行索引。顺便说一句,列索引相同,因为用户可能已经移动了列

于 2013-09-20T09:10:30.167 回答