将组件保留在后台,以便稍后在 javafx 中重用它们



在我的应用程序中,我有一些不同功能需要的组件。
现在,每次我打开一个需要其中一个组件的函数时,所有组件都是从头开始构建的。
这是不必要的,所以我想改变它,但我不知道如何改变。
我不再需要的组件应该隐藏在后面,当再次需要它们时,它们应该放在前面。
这应该可以提高性能,因为组件不需要重建(或者至少我希望如此)。
我希望有人知道我如何解决这个问题。

听起来您在这里需要的只是懒惰地实例化您需要的每个部分,并保留对它的引用。这个问题非常笼统,所以很难给出一个具体的例子,但基本思想看起来像这样:

public class SceneController {
private Parent view1 ;
private Parent view2 ;
// etc... You could perhaps store these in a map, or other data structure if needed
public Parent getView1() {
if (view1 == null) {
view1 = createView1();
}
return view1 ;
}
public Parent getView2() {
if (view2 == null) {
view2 = createView2();
}
return view2 ;
}
private Parent createView1() {
// Build first view. (Could be done by loading FXML, etc.)
}
private Parent createView2() {
// Build second view...
}
}

然后你可以按照以下方式做事

public class MyApp extends Application {
@Override
public void start(Stage primaryStage) {
SceneController sceneController = new SceneController();
BorderPane root = new BorderPane();
Button showView1 = new Button("View 1");
Button showView2 = new Button("View 2");
ButtonBar buttonBar = new ButtonBar();
buttonBar.getButtons().addAll(showView1, showView2);
root.setTop(buttonBar);
showView1.setOnAction(e -> root.setCenter(sceneController.getView1()));  
showView2.setOnAction(e -> root.setCenter(sceneController.getView2()));
Scene scene = new Scene(root, 600, 600);
primaryStage.setScene(scene);
primaryStage.show();
}
}

最新更新