JavaFx-以静态方式初始化场景

JavaFx- initializing scenes in a static way

我想创建一个最终的 class,只有静态方法 - 不需要此 class 的实例 - 它应该是一个静态容器。这个 class 应该有一个包含 created scenes 的地图字段。现在的问题是 - 方法 getClass() 不是静态的,我不能将它包含在我的静态初始化程序块中。有没有一种方法可以在不使用非静态方法的情况下从 FXML 文件创建场景?

代码如下:

package gui;

import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;

import java.util.Map;
import java.util.TreeMap;

public class ViewManager {

    /**
     * Class containing constant height and width of the window. 
     */
    public static final class Bounds{
        public static final int HEIGHT = 800;
        public static final int WIDTH = 800;
    }

    /**
     * Enum class containing paths to following scenes. 
     */
    public enum SceneName{
        LOGIN_VIEW("/login_view.fxml"),
        MAIN_VIEW("/main_view.fxml");

        private String path;

        SceneName(String path) {
            this.path = path;
        }

        @Override
        public String toString() {
            return path;
        }
    }

    private static Map<SceneName, Scene> sceneContainer;

    static{
        sceneContainer = new TreeMap<>();

        for(SceneName sceneName : SceneName.values()) {
            //here is the non-static reference
            Parent root = FXMLLoader.load(getClass().getResource(SceneName.LOGIN_VIEW.toString())); 
            sceneContainer.put(SceneName.LOGIN_VIEW, new Scene(root, Bounds.HEIGHT, Bounds.WIDTH));
        }
    }

    public static Map<SceneName, Scene> getSceneContainer() {
        return sceneContainer;
    }

}

如果您只需要访问某个 Class 实例,只需使用 ClassName.class:

// also changed this to use the loop variable instead of loading the same scene twice
Parent root = FXMLLoader.load(ViewManager.class.getResource(sceneName.toString()));
sceneContainer.put(sceneName, new Scene(root, Bounds.HEIGHT, Bounds.WIDTH));

一般来说,应该避免过于频繁地使用 static。单身人士可能是更好的选择。如果您能够将 ViewManager 实例传递给所有需要它的 类 则更好...(看看依赖注入可能是个好主意。)