JAVAFX - FXML - Access Loaded FXML Controls from Parent Controller

僤鯓⒐⒋嵵緔 提交于 2019-12-13 06:12:18

问题


Here is what I am trying to accomplish.

/Package A/
/Package A/ApplicationController.java
/Package A/Application.fxml

In my Application.fxml file I have a button, and when that button is clicked it loads the following "MyGrid.fxml" file.

/Package B/
/Package B/MyGrid.fxml (has a label #mygridlabelid

The code I am using is:

ContentPane.getChildren().add((Node)FXMLLoader.load(getClass().getResource("/Package B/MyGrid.fxml")));

But the problem is.. even though I am loading the MyGrid.fxml file from the ApplicationController, I cannot access #mygridlabelid from the ApplicationController file. I defined @FXML label mygridlabelid in the ApplicationController.java file, but it doesn't get instantiated :(

How can I do that? Any tricks or hacks around it?


回答1:


I managed to solve the problem by doing the following... and make sure that the .fxml file does not have fx:controller set. Or else you will run into "Controller value already specified."

    FXMLLoader loader = new FXMLLoader(getClass().getResource("/your.fxml"));
    loader.setController(this);
    try {
        ContentPane.getChildren().add((Node)loader.load());
    } catch (IOException e){
        System.out.println(e.getMessage());
    }


来源:https://stackoverflow.com/questions/17801365/javafx-fxml-access-loaded-fxml-controls-from-parent-controller

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!