小编pie*_*isi的帖子

JavaFX从FXML子访问父控制器类

使用JavaFX作为应用程序,我有一个Main.fxml文件,里面有一些fxml子文件.

我想从子控制器访问Main.fxml的MainController类.

我将尝试用一个例子更好地解释:

MainFxml:

    <HBox fx:controller="MainController.java">
        <fx:include source="child.fxml"/>
    </HBox>
Run Code Online (Sandbox Code Playgroud)

MainController:

    public class MainController implements Initializable {
            private String string;
            public void setString (String string) {
                    this.string = string;
            }
Run Code Online (Sandbox Code Playgroud)

ChildFxml:

    <HBox fx:id="child" fx:controller="ChildController.java">
        <Button text="hello" onAction="#selectButton"></Button>
    </HBox>
Run Code Online (Sandbox Code Playgroud)

ChildController:

    public class ChildController implements Initializable {
            @FXML HBox child;
            @FXML Button button;
            @FXML
            public void selectButton (ActionEvent event) {
                // here call MainController.setString("hello");
            }
Run Code Online (Sandbox Code Playgroud)

我尝试在StackOverflow上找到这个解决方案,但我需要获取已经加载的Main.fxml的Controller引用.是否有任何方法可以从特定的窗格启动Controller?就像是:

    // child.getParent().getController();
Run Code Online (Sandbox Code Playgroud)

java javafx fxml

6
推荐指数
1
解决办法
4640
查看次数

标签 统计

fxml ×1

java ×1

javafx ×1