java 当用户尝试使用 JavaFx 中的 setOnCloseRequest 关闭应用程序时的警报框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31540500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 18:46:10  来源:igfitidea点击:

Alert Box For When User Attempts to close application using setOnCloseRequest in JavaFx

javajavafxjavafx-8

提问by user3878223

I am trying to prompt the user to confirm they want to close a program before exiting. In the event a task is still being executed, I wanted to confirm that the still wish to exit or give them a chance to allow the task to finish before exiting. I used setOnCloseRequest, but it did not work. Ive used event.consume which just seemed to disable the [x] button. Any suggestions are appreciated. I found a similar question here that did not work for me -> JavaFX stage.setOnCloseRequest without function?

我试图提示用户在退出前确认他们要关闭程序。如果任务仍在执行,我想确认仍然希望退出或给他们机会让任务在退出之前完成。我使用了 setOnCloseRequest,但是没有用。我使用过 event.consume,它似乎禁用了 [x] 按钮。任何建议表示赞赏。我在这里发现了一个对我不起作用的类似问题 -> JavaFX stage.setOnCloseRequest without function?

Public class Sample extends Application {
      @Override
    public void start(Stage stage) throws Exception {

    stage.setOnCloseRequest(event -> {
        NewScanView checkScan = new NewScanView();
        boolean isScanning = checkScan.isScanning();

            Alert alert = new Alert(AlertType.CONFIRMATION);
            alert.setTitle("Close Confirmation");
            alert.setHeaderText("Cancel Creation");
            alert.setContentText("Are you sure you want to cancel creation?");
        if (isWorking == true){

            Optional<ButtonType> result = alert.showAndWait();
            if (result.get() == ButtonType.OK){
                stage.close();
            }

            if(result.get()==ButtonType.CANCEL){
                alert.close();
            }

        }


    });
    stage.setHeight(600);
    stage.setWidth(800);
    stage.setTitle("Title");
    stage.show();

}

public static void main(String[] args) {
    launch(args);
}

}

}

回答by jewelsea

This answer is based on the answer to Javafx internal close request. That question is different from this question, but the answer is very similar.

此答案基于对Javafx internal close request的回答。这个问题与这个问题不同,但答案非常相似。

maindialog

主要的对话

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.StackPane;
import javafx.stage.*;
import javafx.stage.WindowEvent;

import java.util.Optional;

public class CloseConfirm extends Application {

    private Stage mainStage;

    @Override
    public void start(Stage stage) throws Exception {
        this.mainStage = stage;
        stage.setOnCloseRequest(confirmCloseEventHandler);

        Button closeButton = new Button("Close Application");
        closeButton.setOnAction(event ->
                stage.fireEvent(
                        new WindowEvent(
                                stage,
                                WindowEvent.WINDOW_CLOSE_REQUEST
                        )
                )
        );

        StackPane layout = new StackPane(closeButton);
        layout.setPadding(new Insets(10));

        stage.setScene(new Scene(layout));
        stage.show();
    }

    private EventHandler<WindowEvent> confirmCloseEventHandler = event -> {
        Alert closeConfirmation = new Alert(
                Alert.AlertType.CONFIRMATION,
                "Are you sure you want to exit?"
        );
        Button exitButton = (Button) closeConfirmation.getDialogPane().lookupButton(
                ButtonType.OK
        );
        exitButton.setText("Exit");
        closeConfirmation.setHeaderText("Confirm Exit");
        closeConfirmation.initModality(Modality.APPLICATION_MODAL);
        closeConfirmation.initOwner(mainStage);

        // normally, you would just use the default alert positioning,
        // but for this simple sample the main stage is small,
        // so explicitly position the alert so that the main window can still be seen.
        closeConfirmation.setX(mainStage.getX());
        closeConfirmation.setY(mainStage.getY() + mainStage.getHeight());

        Optional<ButtonType> closeResponse = closeConfirmation.showAndWait();
        if (!ButtonType.OK.equals(closeResponse.get())) {
            event.consume();
        }
    };

    public static void main(String[] args) {
        launch(args);
    }

}

The answer does use event.consume(), which you said you tried and did not work for you (though I'm not sure why not as it works fine for me with this sample code).

答案确实使用了event.consume(),您说您尝试过但对您不起作用(尽管我不确定为什么不这样做,因为使用此示例代码对我来说效果很好)。

回答by SomeStudent

Try creating a popup box (if you haven't) that upon clicking exit will prompt the user. If they select "Ok" then call the exit method, otherwise return to whatever it is you are doing.

尝试创建一个弹出框(如果你还没有),点击退出时会提示用户。如果他们选择“确定”,则调用退出方法,否则返回到您正在执行的任何操作。

Here's a webpage that contains an example as as to how to write your popup as the docs are utter garbage. https://gist.github.com/jewelsea/1926196

这是一个网页,其中包含有关如何编写弹出窗口的示例,因为文档完全是垃圾。https://gist.github.com/jewelsea/1926196