1. 添加点击事件
2. 在MainViewHandler处理类中,实现相应的处理操作
if ("删除".equals(text)){int[] selectedRowIds = mainView.getSelectedRowIds();if (selectedRowIds.length == 0){JOptionPane.showMessageDialog(mainView, "请选择要删除的数据!");return;}int option = JOptionPane.showConfirmDialog(mainView, "确定要删除选中的" + selectedRowIds.length + "条数据吗?","确认删除?", JOptionPane.YES_NO_OPTION);if (option == JOptionPane.YES_OPTION) { // option=0, 表示执行删除操作StudentServiceImpl studentService = new StudentServiceImpl();boolean deleteStudentResult = studentService.deleteStudent(selectedRowIds);if (deleteStudentResult) {mainView.reloadTable();} else {JOptionPane.showMessageDialog(mainView, "删除失败!");}}}
3. 接口
boolean deleteStudent(int[] selectedRowIds);
4. 实现类
// 删除@Overridepublic boolean deleteStudent(int[] selectedRowIds) {StringBuilder sql = new StringBuilder();sql.append("delete from detail where id in ( ");for (int i=0; i<selectedRowIds.length; i++) {if (i == selectedRowIds.length-1) {sql.append(" ? ");} else {sql.append(" ?, ");}}sql.append(" ) ");// 执行Connection connection = null;PreparedStatement preparedStatement = null;ResultSet resultSet = null;TableDTO tableDTO = new TableDTO(); // 返回的数据try {connection = DBUtil.getConnection();preparedStatement = connection.prepareStatement(sql.toString());for (int i=0; i<selectedRowIds.length; i++) {// 设置参数,从 1 开始preparedStatement.setInt(i+1, selectedRowIds[i]);}return preparedStatement.executeUpdate() == selectedRowIds.length; // 执行查询返回结果集(返回相应删除的数量)}catch (Exception e) {e.printStackTrace();} finally {DBUtil.closeRS(resultSet);DBUtil.closePS(preparedStatement);DBUtil.closeConnection(connection);}return false;}
5. 效果展示