setOnCloseRequest的Java FXML
问题描述:
嗯,我使用JavaFX FXML,也不仅仅是JavaFX的信息少,所以我可以使用MVC,但我有麻烦,添加一个确认对话框,如果我按Alt + F4或退出按钮窗口,会显示一个确认对话框。setOnCloseRequest的Java FXML
我发现this,把一个事件放在setOnCloseOperation上,完成这项工作。
答
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.ButtonType;
import javafx.stage.Modality;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
public class Main extends Application {
@Override
public void start(Stage stage) throws Exception {
Parent root = FXMLLoader.load(getClass().getResource("close.fxml"));
Scene scene = new Scene(root);
stage.setOnCloseRequest(e -> {
e.consume(); // stop the event to do something before quitting
closeRequest(stage); // method used to show a confirmation dialog
});
stage.setScene(scene);
stage.show();
}
private void closeRequest(Stage stage){
String msg =
"Sure to quit?";
Alert alerta = new Alert(Alert.AlertType.CONFIRMATION);
alerta.initStyle(StageStyle.DECORATED);
alerta.initModality(Modality.APPLICATION_MODAL);
alerta.initOwner(stage);
alerta.getDialogPane().setContentText(msg);
alerta.getDialogPane().setHeaderText(null);
alerta.showAndWait()
.filter(response -> response == ButtonType.OK)
.ifPresent(response -> { stage.close(); }); // then we need to call the close method for a stage, if the response is ok.
}
public static void main(String[] args) {
launch(args);
}
}
所以在你的主类中,加载fxml资源的那个类,你需要使用方法setOnCloseOperation。
最前一页需要那么你停下来完成程序消耗事件。 然后我们调用一个方法来显示一个确认框,然后我们可以调用.close方法来关闭舞台。