简体   繁体   English

JAVAFX - FXML - 从父控制器访问加载的FXML控件

[英]JAVAFX - FXML - Access Loaded FXML Controls from Parent Controller

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. 在我的Application.fxml文件中,我有一个按钮,当单击该按钮时,它会加载以下“MyGrid.fxml”文件。

/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. 但问题是..即使我从ApplicationController加载MyGrid.fxml文件,我也无法从ApplicationController文件访问#mygridlabelid。 I defined @FXML label mygridlabelid in the ApplicationController.java file, but it doesn't get instantiated :( 我在ApplicationController.java文件中定义了@FXML标签mygridlabelid,但它没有实例化:(

How can I do that? 我怎样才能做到这一点? Any tricks or hacks around it? 围绕它的任何技巧或黑客?

I managed to solve the problem by doing the following... and make sure that the .fxml file does not have fx:controller set. 我设法通过执行以下操作来解决问题...并确保.fxml文件没有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());
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM