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
View all comments
Show parent comment
2
u/hamsterrage1 Dec 26 '24
How many layouts do you have?
Strings as keys to Maps always strikes me as a bit of a code smell - unless you have hundreds of keys and it's open-ended by design. Almost always, some sort of an Enum would be better, IMHO. If you were clever, you could even put the layouts inside the Enum as a field.
Using FXML files makes everything in code a bit more difficult, but not so much in this case. You have some "master" layout and it has a container class like StackPane in in it. You load all of your FXML files up and get a bunch of root items, all assigned to variables or Enum fields or Map values. Then you put all of those root Nodes into the StackPane's children List.
Then you forget about the master layout and its StackPane, you just deal with those root Nodes, wherever you stored them. Set up some logic system that turns all of the visibleProperty()'s and managedProperty()'s to false, except for the one that you want to see.
QED.