Prevent/Cancel closing of primary stage in JavaFX 2.2

前端 未结 4 552
小蘑菇
小蘑菇 2020-12-15 17:17

As the title says, my question is, how can I prevent/cancel closing of primary stage in JavaFX 2.2? I have done some research on Google, and the following two links seemed t

相关标签:
4条回答
  • 2020-12-15 17:53

    I think you got the onCloseRequest() concept wrong. If you consume the event you cancel the closing! So it works the other way round, if canExit() returns false you consume the event

    0 讨论(0)
  • 2020-12-15 18:04

    I have used following code in my application and it works perfectly,

    Platform.setImplicitExit(false);
    
    primaryStage.setOnCloseRequest(new EventHandler<WindowEvent>() {
        @Override
        public void handle(WindowEvent event) {
            event.consume();
        }
    });
    
    0 讨论(0)
  • 2020-12-15 18:10

    I think this is a bug with JavaFX for Linux. I ran in to the same problem on Javafx 2.2.21-b11. Depending on the context the GTK errors may or may not be present, but either way consuming the close request event didn't prevent the window from closing (yet the process continues to run). The same app on Windows behaved as I would expect. So at best we have a difference in behavior across platforms.

    I filed a bug report you can upvote if you'd like: https://javafx-jira.kenai.com/browse/RT-33295

    Here's the source of my test app

    import javafx.application.Application;
    import javafx.event.EventHandler;
    import javafx.stage.Stage;
    import javafx.stage.WindowEvent;
    
    public class Boom extends Application {
        @Override
        public void start(final Stage primary)  {
            System.out.println(com.sun.javafx.runtime.VersionInfo.getRuntimeVersion());
            primary.setOnCloseRequest(new EventHandler<WindowEvent>() {
                @Override
                public void handle(WindowEvent e) {
                    e.consume();
                }
            });
            primary.show();
        }
    
        public static void main(String[] args) {
            launch(args);
        }
    }
    
    0 讨论(0)
  • 2020-12-15 18:19

    That worked for me

                    stage.setOnCloseRequest(new EventHandler<WindowEvent>() {  
                        @Override
                        public void handle(WindowEvent event) {
                            AlertHelper addMore = new AlertHelper("Exit application? Any unsaved data will be lost", "Attention", "Confirmation Required");
                            boolean actionNeeded = addMore.populatePopup();
                            if (actionNeeded) {
                                System.exit(0);
                            } else {
                                event.consume();
                            }
    
                        }
                    });
    
    0 讨论(0)
提交回复
热议问题