I have a program with few fxml files so at different points of program different scene and layout is shown.
some point in a program:
mainStage.setScene(FXMLScene1);
...
later in a program:
mainStage.setScene(FXMLScene2);
...
later in a program:
mainStage.setScene(FXMLScene2);
I wonder what happens to old scene when I use setScene()
several times?
There are very complicated methods to change scene(like this https://blogs.oracle.com/acaicedo/entry/managing_multiple_screens_in_javafx1) and my solution is just to make static refference to main stage at MainApplication class so I can manage it everywhere.
public class MainApplication extends Application {
public static Stage parentWindow;
@Override
public void start(Stage stage) throws Exception {
parentWindow = stage;
so it made me wonder if everything is allright with my concept...
If you set a new scene on your stage and keep no reference to the old scene or objects in it, the old scene will be garbage collected and all resources associated with it will be thrown away (whenever the garbage collector in the Java Virtual Machine decides to do so). If you keep a reference to the old scene (e.g. assign it to a static final variable in your application), then the old scene resources will remain in memory until your application terminates.
If I change the root, how to make Stage change to the new size(size of Layout)?
Use stage.sizeToScene()
, which will: "Set the width and height of this Window to match the size of the content of this Window's Scene." The stage sizing process when you invoke this call is similar to when you initially show a stage, but updated for the current scene's content and layout constraints.
The algorithm used is documented in the Scene javadoc: "The scene's size may be initialized by the application during construction. If no size is specified, the scene will automatically compute its initial size based on the preferred size of its content. If only one dimension is specified, the other dimension is computed using the specified dimension, respecting content bias of a root."
what is better, to change the whole scene, or just a root?
I don't think it makes much difference, choose whichever strategy makes the most sense to you.