Lukas
Lukas

Reputation: 451

How to properly show an alert during initialize?

In my initialize() method of Controller MyController I use a SQL query to initialize the values of a combobox. But when e.g. the user is not online, I would get an error and then I would like to show an Alert.

But the problem is, if I do so in the initialize() method, first the Alert will be shown and then the initialized fxml myfxml, so the Alert is hidden by it. I guess the reason is that, during the initialize() method, myfxml doesn't have a Stage yet, since it is still initializing and so my Alert is shown on another Stage.

But what would be the recommended way to solve this and show the Alert with the initializing method as Parent? One way I found was to save the Exception in MyController, create a getter and call a method like this:

MyController myCon = ((MyController)fxmlLoader.getController());
SQLException e = myCon.getInitializeException();
new Alert(Alert.AlertType.WARNING, e.getMessage());

But since myfxml gets initialized in MenuController's initialize method, I would need to repeat the code again which would mess up my Code.

So is there a clean way to solve my problem?

Thank you in advance :)!

Upvotes: 1

Views: 201

Answers (1)

Jochen Reinhardt
Jochen Reinhardt

Reputation: 843

Try using Platform.runLater(...) in your initialize method. The platform thread will execute the code after your window is completely initialized and shown. You should be able to get a reference to the window using any control via cntrl.getScene().getWindow(). This can be passed on to Alert.initOwner(...).

BTW, you should not run SQL queries from the JavaFX Platform thread. This will make your application not respond to any kind of user input. E.g., your window will not get drawn correctly when the user moves it around. Make sure that you access the database from within a different thread. You could use Excecutors and ExecutorService or a plain Thread. Use Platform.runLater(...) to pass the results towards the front-end and update your UI controls accordingly.

Upvotes: 5

Related Questions