2013-02-21 132 views
4

我有如下從「從父控制器訪問子控制器」上的stackoverflow代碼。JavaFX 2.2 -fx:include - 如何從子控制器訪問父控制器

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。任何幫助將appriciated。

回答

3

我做如下 -

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和child.getParent的mClicked方法().lookup,搜索Id並返回節點。