通过FXML管理JavaFX中的场景切换(性能问题)

时间:2018-10-22 13:16:17

标签: java javafx fxml

我正在与JavaFX和FXML加载的各种场景进行交互。因此,我想到了写一个负责场景切换的管理器的想法。

到目前为止,一切正常,但是我不确定这是否是一个好的实现。

import java.io.IOException;
import javafx.fxml.FXMLLoader;
import javafx.scene.Scene;
import javafx.scene.layout.Pane;
import javafx.stage.Stage;

public class SceneManager {
    private static final String[] fxmlFiles = {"../gui/MainWindow.fxml", "../gui/NewGameWindow.fxml"};
    private static SceneManager instance = null;
    private static Stage rootStage = null;

    private FXMLLoader[] loadedFxml;
    private Pane[] loadedPanes;
    private Scene[] scenes;

    public enum States {
        MAIN_MENU, NEW_GAME;
    }

    private SceneManager() {
        try {
            this.loadedFxml = new FXMLLoader[States.values().length];
            this.loadedPanes = new Pane[States.values().length];
            this.scenes = new Scene[States.values().length];

            for(int i = 0; i < fxmlFiles.length; i++) {
                loadedFxml[i] = new FXMLLoader(getClass().getResource(fxmlFiles[i]));
                loadedPanes[i] = loadedFxml[i].load();
                scenes[i] = new Scene(loadedPanes[i]);
            }

            rootStage.setScene(scenes[0]);
            rootStage.setResizable(false);
            rootStage.show();
        } catch(IOException e) {
            e.printStackTrace();
        }
    }

    public static SceneManager getInstance() {
        if(instance == null) {
            instance = new SceneManager();
        }
        return instance;
    }

    public static void setUp(Stage stage) {
        SceneManager.rootStage = stage;
    }

    public void switchScene(States state) {
        rootStage.setScene(scenes[state.ordinal()]);
    }
}

所以我打算做的是,通过加载器加载FXML,将其分配给窗格,创建所有场景。

然后我将一个场景设置为其开始场景,然后通过控制器中的getInstance()。switchScene()方法进行其余操作。

效果很好,但是我不确定这是否是一个好方法。

1 个答案:

答案 0 :(得分:2)

实现的糟糕之处有几个原因:

单例模式未正确实现

单例模式用于通过static方法访问包含相关数据/功能的实例,但是此实例应包含所有相关数据作为实例字段。

rootStagesetUpstatic

您将数据存储在不再需要的字段中

您永远不会从循环外的loadedFxmlloadedPanes中读取内容。您可以在循环主体中创建局部变量。

所有内容都立即加载

对于几个小的场景,这可能并没有太大的区别,但是随着您添加越来越多的场景,这将增加启动时间。考虑延迟加载场景。

场景数据保存在不同的数据结构中

没什么大问题,但这使类的维护更加困难。 enum存储用于创建/访问场景的数据的一部分fxmlFiles包含另一半。每次添加/删除场景时,都需要更新代码的两个部分。在这种情况下,最好将网址数据存储在枚举本身中:

public enum States {
    MAIN_MENU("../gui/MainWindow.fxml"), NEW_GAME("../gui/NewGameWindow.fxml");
    private final url;

    States(String url) {
        this.url = url;
    }
}
for(States state : States.values()) {
    FXMLLoader loader = new FXMLLoader(getClass().getResource(state.url));
    ...
}

请注意,如果您将程序打包为jar,则在此处的网址中使用..会停止工作。

但是首先使用enum是一个有问题的决定。这样一来,您将无法在不重新编译的情况下添加/删除场景。

似乎根本不需要使用static

最好尽可能避免使用static。 (请参阅Why are static variables considered evil?)。

如果我假设您仅从加载的场景中使用SceneManager类(并用于显示初始场景)是正确的,那么将SceneManager实例传递给控制器​​的控制器并不难。场景以避免在这些类中使用SceneManager.getInstance(请参见Passing Parameters JavaFX FXML):

控制器的超类

public class BaseController {
    protected SceneManager sceneManager;
    void setSceneManager(SceneManager sceneManager) { // if SceneManager and BaseController are in different packages, change visibility
        this.sceneManager = sceneManager;
    }
}
FXMLLoader loader = ...
Pane pane = loader.load();
BaseController controller = loader.getController();
controller.setSceneManager(this);

为简单起见,使用url作为场景的标识符,您可以改进实现:

public class SceneManager {

    private final Stage rootStage;

    public SceneManager(Stage rootStage) {
        if (rootStage == null) {
            throw new IllegalArgumentException();
        }
        this.rootStage = rootStage;
    }

    private final Map<String, Scene> scenes = new HashMap<>();

    public void switchScene(String url) {
        Scene scene = scenes.computeIfAbsent(url, u -> {
            FXMLLoader loader = new FXMLLoader(getClass().getResource(u));
            try {
                Pane p = loader.load();
                BaseController controller = loader.getController();
                controller.setSceneManager(this);
                return new Scene(p);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });
        rootStage.setScene(scene);
    }
}

这允许您

  • 在不同阶段创建不同的经理
  • 首先需要时加载场景
  • 动态添加更多场景
  • 阻止状态为switchScene的调用null
  • 将对控制器类中的SceneManager的访问简化为sceneManager.switchScene
  • SceneManager可能在程序完成之前可用于垃圾回收,因为没有静态引用。