从 JavaFX 中的另一个控制器访问字段 [英] Access fields from another Controller in JavaFX
问题描述
我正在使用 JavaFX 编写小型应用程序,但我遇到了一个问题.
I'm writing small application using JavaFX but I stuck with one problem.
我有 fxml 文件:
I have fxml files:
MainPane.fxml
Stream.fxml
Play.fxml
他们每个人都有自己的控制器:
and each of them has its own controller:
MainPaneController.java
StreamController.java
PlayController.java
MainPane 中的位置:
Where in MainPane is:
<GridPane fx:controller="model.MainController" fx:id="mainGrid"
xmlns:fx="http://javafx.com/fxml" alignment="CENTER" gridLinesVisible="true">
<children>
<fx:include source="Stream.fxml"/>
</children>
<children>
<fx:include source="Play.fxml"/>
</children>
</GridPane>
Play.fxml 有这个字段:
Play.fxml has this field:
<TextField fx:id="searchField" text="Search" onAction="#search"/>
现在,如果触发操作(输入按钮),我想访问和更改 Stream.fxml 中的标签,如下所示:
now when action (enter button) if fired I want to access and change a label in Stream.fxml as follows:
public class PlayController implements Initializable {
@FXML
private TextField searchField;
@FXML
protected void search() {
System.out.println("Search");
String text = searchField.getText();
//how to access Label in StreamController
}
}
我想避免绑定
MainPaneController <-> StreamController
MainController <-> PlayController
和访问字段,如:
mainController.getStreamController.changeLabel(text)
因为我希望有更好的方法来做到这一点.
because I hope there is some better way to do this.
推荐答案
在嵌套"控制器 StreamController 和 PlayController 中公开属性.这些控制器可以根据需要将属性绑定到他们定义的 UI 组件.
Expose properties in the "nested" controllers StreamController and PlayController. Those controllers can bind the properties to the UI components they define as needed.
然后按照FXML 简介的嵌套控制器部分.
更新:这是一个更相似的示例,其中交互控制器都包含在一个公共FXML.
Update: Here's a more similar example, where the interacting controllers are both included in a common FXML.
这篇关于从 JavaFX 中的另一个控制器访问字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!