我正在尝试创建一个库存管理程序,并且当用户按下取消按钮时,我需要打开一个确认对话框。所有示例似乎都非常简单明了,但是我的警报没有打开。
AddPartController.java (我保证这不是导入语句所在的位置)
import java.io.IOException;
import java.net.URL;
import java.util.Optional;
import java.util.ResourceBundle;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.control.RadioButton;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
@FXML
private Button addPartCancelBtn;
@FXML
void addPartCancelBtnHandler(ActionEvent event) throws IOException {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Cancel Add Part");
alert.setHeaderText("This part will not be added");
alert.setContentText("Are you ok with this?");
Optional<ButtonType> result = alert.showAndWait();
if(result.isPresent() && result.get() == ButtonType.OK) {
Stage stage;
Parent root;
stage = (Stage) addPartCancelBtn.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
root = loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
System.out.println("OK PRESSED");
} else {
Stage stage;
Parent root;
stage = (Stage) addPartCancelBtn.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("AddPart.fxml"));
root = loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
System.out.println("Errror");
}
}
任何人都可以在这里看到问题吗?
答案 0 :(得分:0)
添加了一个Try Catch块来修复它:
@FXML
void addPartCancelBtnHandler(ActionEvent event) throws IOException {
try {
Alert alert = new Alert(AlertType.CONFIRMATION);
alert.setTitle("Cancel Add Part");
alert.setHeaderText("This part will not be added");
alert.setContentText("Are you ok with this?");
alert.getDialogPane().setPrefSize(350, 200);
Optional<ButtonType> result = alert.showAndWait();
if(result.isPresent() && result.get() == ButtonType.OK) {
Stage stage;
Parent root;
stage = (Stage) addPartCancelBtn.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("Main.fxml"));
root = loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
System.out.println("OK PRESSED");
} else {
Stage stage;
Parent root;
stage = (Stage) addPartCancelBtn.getScene().getWindow();
FXMLLoader loader = new FXMLLoader(getClass().getResource("AddPart.fxml"));
root = loader.load();
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
System.out.println("Errror");
}
} catch (IOException e) {
e.printStackTrace();
}
}