6

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

父控制器.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) {
    }

}

孩子.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>

父.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。任何帮助都会得到帮助。

4

1 回答 1

4

我做了以下 -

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"));
    }
}

孩子.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 和 child.getParent().lookup 的 mClicked 方法,搜索 Id 并返回节点。

于 2013-03-07T17:49:20.113 回答