Question

My test app's flow uses multiple screens :

start(Stage stage) -> Screen 1
                   -> Screen 2
                   -> ...

I want to implement some of my screens in fxml, but can't figure what's the best practise way to switch between them.

How can i implement some quit-event mechanism in the screen 1 controller, when screen 1 reached its final state, and connect it to the "main loop" to delete screen 1 and update the scene with screen 2 ?

Was it helpful?

Solution

In my opinion, the best way to do it is loading your screens "on demand" whenever they are to be used, or even load them for just certain regions of your main screen (like a tab). To load a screen with FXML and then assign it to your main stage you would do something like:

Parent root = FXMLLoader.load(me.getClass().getResource("Scene2.fxml"));
Scene scene = new Scene( root );
stage.setScene(scene);

Another alternative is to use multiple stages, launch a stage whenever you need to do a specific action. This stage can be modal, so when it is closed, the main window stays behind:

final  Stage stage = new Stage();     
stage.initStyle(StageStyle.UNDECORATED);
stage.initOwner(owner_stage);
stage.initModality(Modality.APPLICATION_MODAL);

In this later case, the "quit mechanism" is just hiding the scene:

// from a label of your controller class
label.getScene().getWindow().hide();  

In the first case, you would just load the main scene in your stage. Using multiple stages is the most common and straightforward way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top