JavaFX 控制器加载

JavaFX Controller loading

每次忘记技巧时,我都会遇到一些非常奇怪的行为。

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = loader.load();
GuiController controller = loader.getController();

现在 controller 不为空。

然而,在我这样做之后...

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = loader.load(getClass().getResource("view/window.fxml"));
GuiController controller = loader.getController();

controller 现在是 null

我知道 loader 不知何故失去了对位置的控制?我非常感谢有人告诉我这是预期的行为并解释原因。

请注意,关于这个问题,post 找了好久都没找到,并且在实验 2 小时后才找到解决方案,所以请不要 link 我提出类似的问题问题。

FXMLLoader 方法 load(URL) 是一种 static 方法。所以你的第二个代码块相当于 (compiles to)

FXMLLoader loader = new FXMLLoader();
// I assume you mean loader, not fxmlLoader, in the next line:
loader.setLocation(getClass().getResource("view/window.fxml"));
Parent root = FXMLLoader.load(getClass().getResource("view/window.fxml"));
GuiController controller = loader.getController();

换句话说,您永远不会在 loader 上调用 load(...):因此 loader 永远不会解析 FXML,也永远不会实例化控制器。

在您的第一个代码块中,您调用了无参数 load() 方法,这是一个实例方法。