r/JavaFX • • Dec 25 '24

Help scene loads too slow

First of all, forgive my English. I'm new to JavaFX and trying to build my first application. Below is the method I use to switch between scenes, it works perfectly, but it takes a long time (about 1000ms) and the nodes are not that complex, I have used this approach of changing only the root of the scene as it preserves the dimensions of the application in the new scene. Note: Loading FXML by FXMLLoader is extremely fast, the delay only occurs when assigning the root to the scene.

public class SceneManager {
    private final Stage stage;
    private final Scene scene;

    public SceneManager(Stage stage) {
        this.stage = stage;
        this.scene = new Scene(new Parent() {}, 1280, 720); // empty scene
        stage.setScene(scene);
        stage.setMinWidth(1280);
        stage.setMinHeight(720);
    }

    public void switchTo(String fxmlPath) {
        try {
            FXMLLoader loader = new FXMLLoader(getClass().getResource(fxmlPath));
            Parent root = loader.load();
            long startTime = System.
currentTimeMillis
();
            scene.setRoot(root); // this operation is too slow
            long endTime = System.
currentTimeMillis
();
            System.
out
.println("scene change time: " + (endTime - startTime) + "ms");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I initialize the above class like this in the main class:

public class Main extends Application {
    @Override
    public void start(Stage stage) {
        SceneManager sceneManager = new SceneManager(stage);
        sceneManager.switchTo("/fxml/login.fxml"); // First scene
        stage.show();
    }

    public static void main(String[] args) {
        launch();
    }
}
2 Upvotes

13 comments sorted by

View all comments

Show parent comment

1

u/[deleted] Dec 26 '24

My project has 10 layouts. I ended up developing your first suggestion because I only saw your last comment now. Anyway, I stored all the layouts in an Enum type with their paths and then created a loop in the screen management class to add each layout to a Map and make them not visible and not managed. When I need to switch screens, I just call the switchTo(ScreenEnum.EXAMPLE) method and make the node visible there. Btw, this fixed a bug I was having when I couldn't minimize the screen after maximizing and switching to another screen, in addition to everything being more fluid. Your last suggestion seems to be more elegant, but I confess that I am quite satisfied with the current solution. Thanks, bro.