Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaFX 2.2 -fx:include - how to access parent controller from child controller

I had code from stackoverflow on "access child controller from parent controller" as below.

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>

My Query - I want to access lebelInParent of parent.fxml from childController.java. Any help will be appriciated.

like image 631
Abhishek Kumar Avatar asked Feb 21 '13 14:02

Abhishek Kumar


1 Answers

I did as following -

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>

explaination - it loads parent.fxml and when I click on sessionLabel, it calls mClicked method of childController and child.getParent().lookup, search for Id and return Node.

like image 186
Abhishek Kumar Avatar answered Nov 15 '22 11:11

Abhishek Kumar