-1

这是我的表模型:

public class d9 extends AbstractTableModel {

ArrayList<String> cols = new ArrayList<>();
ArrayList<ArrayList<String>> data = new ArrayList<>();

public d9() {
...
int c = resultSet.getMetaData().getColumnCount();
            while (resultSet.next()) {
            ArrayList<String> eachRow = new ArrayList<>();
            for (int i = 1; i <= c; i++) {
                eachRow.add(resultSet.getString(i));
            }
            data.add(eachRow);
        }
...
}

@Override
public int getRowCount() {
return data.size();
}

@Override
public int getColumnCount() {
return cols.size();
}

@Override
public Object getValueAt(int rowIndex, int columnIndex) {
ArrayList<String> selectedRow = data.get(rowIndex);
return selectedRow.get(columnIndex);
}

@Override
public String getColumnName(int column) {
return cols.get(column);
}

public void removeRow(int rowNumber) {
data.remove(rowNumber);
fireTableRowsDeleted(rowNumber, rowNumber);
}
}

现在,将convertRowIndexToModel行号传递给removeRow方法 Row 从表中删除后,但重新运行程序后,它又回来了!

4

1 回答 1

3

当您打电话时,removeRow您需要尝试从数据库中删除该行。

现在因为我不知道您的数据库的结构是什么,您需要填写详细信息,但这是您需要做的简单概述

public void removeRow(int rowNumber) throws SQLException {
    Connection con = ...;
    PreparedStatement ps = null;

    String keyValue = ...; // Get key value from the ArrayList

    try {
        ps = con.prepareStatement("DELETE from youDatabaseTabe where key=?");
        ps.setObject(1, keyValue);
        if (ps.executeUpdate() == 1) {
            data.remove(rowNumber);
            fireTableRowsDeleted(rowNumber, rowNumber);
        } else {
            throw new SQLException("Failed to remove row from database");
        }
    } finally {
        try {
            ps.close();
        } catch (Exception e) {
        }
    }
}

您可能想花一些时间阅读JDBC 数据库访问

于 2013-07-31T07:26:11.310 回答