JavaFX 2.2 -fx:include – 如何从子控制器访问父控制器

我有来自stackoverflow的代码“从父控制器访问子控制器”,如下所示.

ParentController.java

public class ParentController  implements Initializable{

    @FXML private childController childController;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        childController.sessionLabel.setText("Real blabla");
        System.out.println("sessionLabel= " + childController.sessionLabel.getText());
    }

}

childController.java

public class childController  implements Initializable{

    @FXML public Label sessionLabel;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }

}

child.fxml

<AnchorPane maxHeight="20.0"  prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="childController">
   <children>
      <HBox id="hbox_top" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
         <Label fx:id="sessionLabel" prefHeight="20.0" text="" />  
      </HBox>
   </children>
</AnchorPane>

parent.fxml

<AnchorPane id="AnchorPane" prefHeight="400.0" prefWidth="600.0" xmlns:fx="http://javafx.com/fxml" fx:controller="ParentController">
<children>
    <fx:include fx:id="child" source="child.fxml"/>
     <Label fx:id="lebelInParent" prefHeight="20.0" text="" />  
</children>
</AnchorPane>

我的查询 – 我想从childController.java访问parent.fxml的lebelInParent.任何帮助都会得到满足.

最佳答案
我做了如下 –

public class childController  implements Initializable{

    @FXML public Label sessionLabel;
    @FXML private AnchorPane child;

    @Override
    public void initialize(URL location, ResourceBundle resources) {
    }
    @FXML
    private void mClicked (){
        System.out.println(child.getParent().lookup("#lebelInParent"));
    }
}

child.fxml

<AnchorPane fx:id="child" xmlns:fx="http://javafx.com/fxml" fx:controller="childController">
   <children>
      <HBox id="hbox_top" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0">
         <Label fx:id="sessionLabel" prefHeight="20.0" text="" onMouseClicked="#mClicked"/>  
      </HBox>
   </children>
</AnchorPane>

解释 – 它加载parent.fxml,当我点击sessionLabel时,它调用childController的mClicked方法和child.getParent().lookup,搜索Id并返回Node.

转载注明原文:JavaFX 2.2 -fx:include – 如何从子控制器访问父控制器 - 代码日志