您需要为每个 FXML 文件使用不同的控制器,并且fx:id
- 每个文件的带注释的元素将被注入到相应的控制器实例。
当您包含 FXML 文件时,您可以将包含文件的控制器注入到包含文件的控制器中,方法是设置fx:id
属性上的fx:include
元素:
“主”fxml 文件:
<?import javafx.geometry.*?>
// ...
<BorderPane prefHeight="962" prefWidth="1280" xmlns="http://javafx.com/javafx/8.0.40" xmlns:fx="http://javafx.com/fxml/1" fx:controller="application.MyMainController">
<center>
<SplitPane dividerPositions="0.63" BorderPane.alignment="CENTER">
<items>
<fx:include fx:id="another" source="AnotherFile.fxml" />
// ...
</items>
</SplitPane>
</center>
<top>
// ...
</top>
</BorderPane>
在“主控制器”中:
public class MyMainController {
@FXML
private AnotherController anotherController ;
// ...
}
(规则是字段名称是fx:id
属性与"Controller"
附后)。这里AnotherController
是控制器类AnotherFile.fxml
.
例如,现在您可以公开data您需要在“包含的控制器”中访问:
public class AnotherController {
@FXML
private Label oneOfMyLabels ;
public StringProperty textProperty() {
return oneOfMyLabels.textProperty();
}
public final String getText() {
return textProperty().get();
}
public final setText(String text) {
textProperty().set(text);
}
// ...
}
然后你的主控制器可以做类似的事情
anotherController.setText(...);
这当然会更新标签。这保留了封装,因此如果您选择使用另一个控件而不是标签,这些更改不必传播到直接控制器之外。