Java FXML删除预约弹窗异常:重复显示与不显示问题求助
问题分析与修复方案
看起来你遇到的弹窗问题都是代码里的几个小失误导致的,咱们一步步拆解:
核心问题定位
- 删除成功弹窗不显示:你创建了
alert2作为成功提示,但后续错误地操作了之前的确认弹窗alert(把alert2.setContentText写成了alert.setContentText),而且最后调用的是alert.show(),完全没触发alert2的显示。 - 确认弹窗重复出现:因为你在删除逻辑执行后,又调用了一次
alert.show()(也就是原来的确认弹窗),所以用户需要再点一次OK才能继续。 - 额外小问题:页面刷新代码放在了弹窗显示之前,可能导致弹窗还没被用户看到就被页面跳转覆盖。
修复后的代码
// delete selected appointment @FXML void handleDelete(MouseEvent event) throws IOException, SQLException { Appointment ifSelected = appointmentTable.getSelectionModel().getSelectedItem(); if (ifSelected == null){ Alert alert = new Alert(Alert.AlertType.WARNING); alert.setTitle("Deletion Error"); alert.setHeaderText("You didn't choose an appointment to delete."); alert.setContentText("Please click ok in order to choose an appointment for deletion."); alert.showAndWait(); } else{ Alert alert = new Alert(Alert.AlertType.CONFIRMATION); alert.setTitle("Appointment Deletion"); alert.setHeaderText("You are about to delete an appointment record permanantly."); alert.setContentText("If you want to proceed, click ok."); Optional<ButtonType> result = alert.showAndWait(); if (result.isPresent() && result.get() == ButtonType.OK){ // 正确操作alert2的内容设置 Alert alert2 = new Alert(Alert.AlertType.INFORMATION); alert2.setTitle("Deletion Successful"); alert2.setHeaderText("You successfully deleted the appointment with " + ifSelected.getCustomerName()+ " at " + ifSelected.getStartTime() + "."); // 为成功弹窗设置对应内容,而非复用之前的确认弹窗 alert2.setContentText("Click ok to return to the appointment list."); // 显示成功弹窗并等待用户确认 alert2.showAndWait(); // 执行数据库删除操作 Statement stmt = conn.createStatement(); apptID = ifSelected.getAppointmentID(); String sqlDeleteAppointment = "DELETE FROM appointment WHERE appointmentId = " + apptID; Query.makeQuery(sqlDeleteAppointment); // 用户确认成功提示后,再执行页面刷新 Parent root = FXMLLoader.load(getClass().getResource("appointmentScreen.fxml")); scene = new Scene(root); stage.setScene(scene); stage.show(); } } }
关键修改说明
- 把
alert.setContentText改成alert2.setContentText,确保成功弹窗的内容被正确设置 - 把
alert.show()改成alert2.showAndWait(),让成功弹窗正常显示并等待用户操作 - 将页面刷新代码移到成功弹窗的
showAndWait()之后,保证用户能看到成功提示再跳转页面 - 调整了成功弹窗的内容文本,让提示更贴合操作场景
这样修改后,三个弹窗的逻辑就会完全正常:
- 未选择预约时,正确显示警告弹窗
- 确认删除弹窗点击OK后,不会重复显示
- 删除成功后,正常弹出提示弹窗,用户点击OK后再刷新页面
内容的提问来源于stack exchange,提问作者Cassandra
相关产品推荐
相关产品推荐

