JavaFX 2.2 -fx:include - как получить доступ к родительскому контроллеру с дочернего контроллера

У меня был код из stackru на "доступ дочерний контроллер от родительского контроллера", как показано ниже.

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>

Мой запрос - я хочу получить доступ к lebelInParent для parent.fxml из childController.java. Любая помощь будет оценена.

1 ответ

Решение

Я сделал следующим образом -

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, он вызывает mClicked метод childController и child.getParent().lookup, ищет I d и возвращает Node.

Другие вопросы по тегам