【问题标题】:JavaFX stage.setOnCloseRequest without function?JavaFX stage.setOnCloseRequest 没有功能?
【发布时间】:2014-04-18 19:06:00
【问题描述】:

这是我的开始方法。首先我创建一个舞台并设置一个标题和一个场景。如果有人想关闭 window-close-btn [X] 上的窗口,我想创建一个对话框。我想我会用 setOnCloseRequest() 函数来捕捉这个事件。但我仍然可以关闭我在运行时打开的所有阶段。

@Override
public void start(final Stage primaryStage) throws Exception {
    primaryStage.setTitle("NetControl");
    primaryStage.setScene(
            createScene(loadMainPane())
    );

    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(final WindowEvent event) {
            //Stage init
            final Stage dialog = new Stage();
            dialog.initModality(Modality.APPLICATION_MODAL);

            // Frage - Label
            Label label = new Label("Do you really want to quit?");

            // Antwort-Button JA
            Button okBtn = new Button("Yes");
            okBtn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    dialog.close();
                }
            });

            // Antwort-Button NEIN
            Button cancelBtn = new Button("No");
            cancelBtn.setOnAction(new EventHandler<ActionEvent>() {
                @Override
                public void handle(ActionEvent event) {
                    primaryStage.show();
                    dialog.close();
                }
            });
        }
    });

    primaryStage.show();
}

private Pane loadMainPane() throws IOException {
    FXMLLoader loader = new FXMLLoader();

    Pane mainPane = (Pane) loader.load(
            getClass().getResourceAsStream(ContentManager.DEFAULT_SCREEN_FXML)
    );

    MainController mainController = loader.getController();

    ContentManager.setCurrentController(mainController);
    ContentManager.loadContent(ContentManager.START_SCREEN_FXML);

    return mainPane;
}

private Scene createScene(Pane mainPane) {
    Scene scene = new Scene(mainPane);
    setUserAgentStylesheet(STYLESHEET_MODENA);
    return scene;
}

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {
    Application.launch(args);
}

还有其他函数可以捕捉窗口事件吗? 或者在primaryStage上运行CloseRequest是否合乎逻辑,我读了一些平台的东西(但我不知道我的问题是否有必要)?

【问题讨论】:

    标签: javafx javafx-8


    【解决方案1】:

    onCloseRequest 处理程序中,调用event.consume();

    这将阻止初级阶段关闭。

    从取消按钮的处理程序中删除primaryStage.show(); 调用,并在确定按钮的处理程序中添加对primaryStage.hide(); 的调用。

    【讨论】:

    • 感谢您的快速答复!它解决了我的问题;)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多