我有两种方法来删除JTable
选定的行。
我在我的 GUI 类中创建了这些方法:
第一的:
public void dellAction() {
if (table.getSelectedRow() > -1) {
int rowToDelete = table.getSelectedRow();
int rowToModel = table.convertRowIndexToModel(rowToDelete);
Object rowId = table.getValueAt(rowToModel, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model1.removeRow(rowToModel);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else JOptionPane.showMessageDialog(null, "Select A Row");
}
第二:
public void delete(DefaultTableModel model, int modelRow) {
if (table.getSelectedRow() > -1) {
Object rowId = model.getValueAt(modelRow, 0);
try {
Connection con;
PreparedStatement ps = null;
con = DriverManager.getConnection(...);
ps = con.prepareStatement("delete from table where id=?");
ps.setObject(1, rowId);
if (ps.executeUpdate() == 1) {
model.removeRow(modelRow);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null, "Select A Row");
}
}