JavaFx setOnCloseRequest & File check wait

2020-05-01 10:57发布

问题:

I have two windows. The first one is been launched if a property file doesn't exist. The second is ( I want it to be) opened if the file already exists OR when the user click the button which creates the file. Here is the code....

try {
        if(f.exists()) {
            input = new FileInputStream("config.properties");
            prop.load(input);
        }

        if(f.exists() && prop.getProperty("name") != null){
            primaryStage.show();
        }else if(prop.getProperty("name") == null || !f.exists()){

            try {
                Stage stage = new Stage();

                FXMLLoader loader = new FXMLLoader(getClass().getResource("summ.fxml"));
                Parent root1 = loader.load();

                stage.setTitle("temp");
                stage.setResizable(false);
                stage.setScene(new Scene(root1));

                stage.showAndWait();

                summController summController = loader.getController();
                String name = summController.getName();
                stage.setOnCloseRequest(e->{

                    if(prop.getProperty("name") != null || f.exists()) {
                        primaryStage.show();
                    }
                });

Before, instead of the setOnCloseRequest, I just had "primaryStage.show();" but this would open the second window no matter what, after closing the first one. So, it would open if I press the button, but also if I clicked the X in the top corner. I don't want it to be. I tried the setOnCloseRequest to check if the user set his name before he quit (basicly if he pressed the button to save) this way, it doesn't show when I close with the X but also doesn't open if the button is pressed. I want it to open when the button is pressed but not the X. I 'think' that the problem might be that when the user press the button, it "instantly" check for the file but it isn't created yet....

Thanks for your answers!

回答1:

If you don't want to close the window, you should consume the close request event:

if(prop.getProperty("name") != null || f.exists()) {
    primaryStage.show();
} else {
    e.consume();
}


标签: java javafx