我使用此代码获取我的JTable
,
但"AWT-EventQueue-0" java.lang.ClassCastException
发生,
public void actionPerformed(ActionEvent e) {
if (e.getSource() == dellButton) {
try {
int rowToDelete = 0;
int rowToModel = 0;
if (table.getSelectedRow() > -1) {
rowToDelete = table.getSelectedRow();
rowToModel = table.convertRowIndexToModel(rowToDelete);
tableModel.removeRow(rowToModel);
}
} catch (SQLException sqle) {
sqle.printStackTrace();
}
}
}
我的TableModel.removeRow()
方法:
...
public void removeRow(int rowNumber) throws SQLException {
String removeQuery = "delete from mytable where id=?";
PreparedStatement pStatement = con.prepareStatement(removeQuery);
pStatement.setInt(1, rowNumber);
int rowsAffected = pStatement.executeUpdate();
}
...
答案 0 :(得分:4)
int rowID = (int) table.getValueAt(selectedRowIndex, 0);
是无用的代码行,
代码行tableModel.removeRow(rowID, rowIndex);
有错误的参数
测试是否选择了任何行,否则选中的行返回-1
一切都可能只有
@Override
public void actionPerformed(ActionEvent e) {
int rowToDelete = 0;
int rowToModel = 0;
if (table.getSelectedRow() > -1) {
rowToDelete = table.getSelectedRow();
rowToModel = table.convertRowIndexToModel(rowToDelete);
model.removeRow(rowToModel);
}
}
请确保您的SelectionMode
,否则您需要在所选行的数组中循环,
table.getSelectionModel().setSelectionMode(
ListSelectionModel.SINGLE_SELECTION);