当用户单击X按钮退出程序时,如何编写一个弹出对话框的编码?

时间:2018-10-28 01:08:52

标签: java eclipse javafx scenebuilder

我正在使用eclipse,java和Scenebuilder构建UI。当用户单击X按钮退出程序时,我需要先保存然后退出弹出对话框。到目前为止,我在SceneBuilder中构建了一个关闭按钮,按下该按钮时会出现一个弹出对话框,但是当我单击X按钮时却没有。 这是我的代码:

public void start(Stage primaryStage) throws Exception 
{
    ...
}

// Save Dialog
public void confirmDialogBox() {

    System.out.println("Hello");
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setTitle("Save Dialog Box");
    alert.setHeaderText("Do you wish to save changes before exiting?");
    alert.setContentText("Choose your option.");
    ButtonType buttonTypeOne = new ButtonType("Yes");
    ButtonType buttonTypeCancel = new ButtonType("No", ButtonBar.ButtonData.CANCEL_CLOSE);
    alert.getButtonTypes().setAll(buttonTypeOne, buttonTypeCancel);


    Thread thread = new Thread(() -> {
        try {
            // Wait for 5 secs
            Thread.sleep(5000);
            if (alert.isShowing()) {
                Platform.runLater(() -> alert.close());
            }
        } catch (Exception exp) {
            exp.printStackTrace();
        }
    });
    thread.setDaemon(true);
    thread.start();
    alert.showAndWait();
    System.out.println("Bye");


}


@Override
public void stop()
{
    System.out.println("Stage is closing");
    // Save file
}

1 个答案:

答案 0 :(得分:1)

您可以简单地通过中断正常的JavaFX生命周期来做到这一点。我们可以捕获任何关闭窗口的请求,然后运行我们自己的进程来允许或拒绝该请求。

我提供了一个简单的应用程序(带有注释)来演示该概念:

import javafx.application.Application;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.ButtonType;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;
import javafx.stage.WindowEvent;

import java.util.Optional;

public class Main extends Application {

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

    @Override
    public void start(Stage primaryStage) {

        // Simple interface
        VBox root = new VBox(5);
        root.setPadding(new Insets(10));
        root.setAlignment(Pos.CENTER);

        // Button to close the window/application
        Button btnExit = new Button("Exit");
        btnExit.setOnAction(event -> {
            if (confirmExit()) {
                primaryStage.close();
            }
        });

        // Now, add a custom handler on the Window event so we can handle the requast ourselves
        primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
            @Override
            public void handle(WindowEvent event) {
                // Run the confirmExit() method and consume the event if the user clicks NO, otherwise Exit
                if (confirmExit()) {
                    primaryStage.close();
                } else {
                    // Consume the event. This prevents the window from closing and the application exiting.
                    event.consume();
                }
            }
        });

        root.getChildren().add(btnExit);

        // Show the Stage
        primaryStage.setWidth(300);
        primaryStage.setHeight(300);
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }

    private boolean confirmExit() {

        // Get confirmation that you want to exit
        Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
        alert.setTitle("Exit?");
        alert.setHeaderText("Are you sure you want to exit?");
        alert.getButtonTypes().setAll(
                ButtonType.YES,
                ButtonType.NO
        );

        // Get the result of the Alert (which button was selected
        Optional<ButtonType> result = alert.showAndWait();

        // Return true if the user clicked YES, false if they click NO or close the alert.
        return result.orElse(ButtonType.NO) == ButtonType.YES;
    }
}

使用此方法,无论用户单击按钮还是关闭窗口,都将调用handleExit()方法。您可以使用该方法来保存文件。