java - 如何编写当用户单击 X 按钮退出程序时出现的弹出对话框的代码?

标签 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
}

最佳答案

您可以通过中断正常的 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() 方法。您可以使用该方法来保存文件。

关于java - 如何编写当用户单击 X 按钮退出程序时出现的弹出对话框的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53027553/

相关文章:

java - 如何将我在结果集中所做的更改转换为 java 中的 sql 查询?

eclipse - 在 JDK 中运行 Eclipse?

javafx-2 - 数据库操作的任务与服务

java - Java中的Pig UDF : Error 1070

java - 在实现接口(interface)的 Java 泛型上强制使用完全相同的类型

java - 在 Maven 模块之间共享静态资源

eclipse - 如何在MacOS上将Eclipse.app移动到/Applications下?

java - 当 JavaFX 中的整个 Pane 发生变化时,我应该有各种 FXML 文件吗?

java - 以编程方式最小化和最大化 Javafx 应用程序

Java - 输出不打印?