2012-04-20 236 views
15

最近我使用JavaFx2.0編寫軟件,但遇到了一個很大的問題,那就是 - 如何訪問Controller類? 對於具有相同類類型的每個控制器類,它們可能會因爲它所依賴的模型而有所不同,所以我想獲得視圖的Controller類併爲其提供指定模型,我可以這樣做嗎? 我試圖通過FXMLLoader獲取控制器,但getController()方法返回null!爲什麼?如何訪問JavaFx 2.0中的Controller類?

1.LightView.java

FXMLLoader loader = new FXMLLoader(); 
anchorPane = loader.load(LightView.class.getResource(fxmlFile));//fxmlFile = "LightView.fxml" 
//controller = (LightViewController) loader.getController();//fail to get controller!it is null 
//I want to -> controller.setLight(light); 

2.LightView.fxml

<AnchorPane ... fx:controller="light.LightViewController" > 

3.LightViewController.java

.... 
private Light light; 
public void initialize(URL arg0, ResourceBundle arg1) 

4.Light.java

.... a simple pojo 

所以,我想要做的是爲每個LightViewController提供一個指定的Light對象(它們來自List)。 任何人都可以幫助我嗎?非常感謝!

+1

可能重複。更新從不同任務的場景值](http://stackoverflow.com/questions/10107829/javafx-2-0-fxml-updating-scene-values-from-a-different-task) – 2012-07-23 01:33:34

+1

也許這個答案可能會有幫助:[http://stackoverflow.com/a/10108788/682495](http://stackoverflow.com/a/10108788/682495)。 – 2012-04-20 08:52:24

回答

49

我使用以下命令:

URL location = getClass().getResource("MyController.fxml"); 

FXMLLoader fxmlLoader = new FXMLLoader(); 
fxmlLoader.setLocation(location); 
fxmlLoader.setBuilderFactory(new JavaFXBuilderFactory()); 

Parent root = (Parent) fxmlLoader.load(location.openStream()); 

這樣fxmlLoader.getController()null

+0

非常感謝!你的方法是我所需要的!謝謝你,安格! – yinger090807 2012-04-20 16:29:44

+13

@ yinger090807你可以[接受答案](http://meta.stackexchange.com/a/5235/160062),這是有幫助的(這似乎是這裏的情況) – oers 2012-07-23 08:39:30

+0

我有一種情況,'fxmlLoader.getController() '沒有那樣工作。但我不知道爲什麼! – cdaiga 2016-09-06 16:30:44

5

除了阿爾夫的答案,我要指出,該代碼可以更短:

URL location = getClass().getResource("MyController.fxml"); 

FXMLLoader fxmlLoader = new FXMLLoader(); 

Parent root = (Parent) fxmlLoader.load(location.openStream()); 

這也適用。

0

使用getResourceAsStream代替:

anchorPane = loader.load(LightView.class.getResourceAsStream(fxmlFile)); 

其簡約,做工精良。 [JavaFX的2.0 + FXML的

0

你可以試試這個...

FXMLLoader loader = new FXMLLoader(); 
    loader.setLocation(getClass().getResource("LightView.fxml")); 
    loader.load(); 
    Parent parent = loader.getRoot(); 
    Scene Scene = new Scene(parent); 
    Stage Stage = new Stage(); 
    LightViewController lv = loader.getController(); 
    lv.setLight(light); 
    Stage.setScene(Scene); 
    Stage.show(); 
相關問題