2015-11-12 22 views
1

我碰到了一些非常奇怪的行为来几次每遗忘的伎俩时间。的JavaFX的控制器负载

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莫名其妙地失去位置上他的夹子?我非常感谢有人告诉我这是一种预期的行为,并解释了为什么。

请注意,是看了不少关于这个问题没有发现任何岗位后,发现该解决方案唯一的实验2h后,所以请不要用外观相似的问题联系我。

+0

你大概的意思是'loader',不'fxmlLoader'在这两个调用'setLocation(...)'。 –

回答

1

FXMLLoader方法load(URL)static方法。所以,你的第二个代码块相当于(编译成)

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(); 

换句话说,你永远不调用load(...)loader:因此loader从未解析FXML从不实例化控制器。

在你的第一个代码块,你调用无参数load()方法,它是一个实例方法。

+0

没有注意到文档中的'static'关键字。非常感谢你。 :)为此我失去了很多我的晚上。 – ZbyszekKr

+0

由于某种原因,我的警告被压制在这个班上......切换回来后,按照你所说的那样进行。谢谢。 – ZbyszekKr

+0

如果您从参考中调用静态方法,大多数IDE都会给出警告。 –