【问题标题】:setOnCloseRequest Java FXMLsetOnCloseRequest Java FXML
【发布时间】:2017-10-11 17:44:14
【问题描述】:

嗯,我使用的是 JavaFX FXML,信息比 JavaFX 少,所以我可以使用 MVC,但是我无法添加确认对话框,所以如果我在窗口中按 alt + f4 或退出按钮,将显示一个小的确认对话框。

我找到了this,在 setOnCloseOperation 上设置了一个事件,就可以了。

【问题讨论】:

    标签: java model-view-controller javafx-8


    【解决方案1】:
    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 方法来关闭舞台。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-28
      • 1970-01-01
      相关资源
      最近更新 更多