JavaFX 2.2 -fx:include - 如何从子控制器访问父控制器 [英] JavaFX 2.2 -fx:include - how to access parent controller from child controller
问题描述
我有来自 stackoverflow 的关于从父控制器访问子控制器"的代码,如下所示.
I had code from stackoverflow on "access child controller from parent controller" as below.
父控制器.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
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>
父.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.任何帮助都会得到认可.
My Query - I want to access lebelInParent of parent.fxml from childController.java. Any help will be appriciated.
推荐答案
我做了如下 -
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().lookup 的 mClicked 方法,搜索 Id 并返回节点.
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.
这篇关于JavaFX 2.2 -fx:include - 如何从子控制器访问父控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!