我更喜欢的一种选择是使用自定义组件,而不是
<fx:include fx:id="analysisTab"source="FileListTab.fxml" />。因此,在中
Main.fxml,将
<fx:include>行替换为:
<FileList fx:id="fileList"></FileList>
FileList是我们新的自定义组件。您还必须添加
<?importyourpackage.*?>到的顶部
Main.fxml,以使
yourpackageFXML可以使用这些类。(显然,
yourpackage该软件包包含此问题中的所有类和文件。)
在下面添加的是
yourpackage.FileList.java;中的自定义组件的类。您的代码大部分来自
FileListController+加载FXML所需的代码。但是请注意,它扩展了JavaFX组件
VBox,使它本身成为FXML组件。该
VBox是你的根组件
FileListTab.fxml,因此也必须在声明
type的属性
FileList.fxml如下。
package yourpackage;import java.io.IOException;import javafx.fxml.FXML;import javafx.fxml.FXMLLoader;import javafx.scene.control.Label;import javafx.scene.layout.VBox;public class FileList extends VBox { private Model model; // NOT REALLY NEEDED! KEEPING IT BECAUSE YOUR FileListController HAD IT TOO... @FXML Label label_rootFolder; public FileList() { java.net.URL url = getClass().getResource("/yourpackage/FileList.fxml"); FXMLLoader fxmlLoader = new FXMLLoader(url); fxmlLoader.setRoot(this); fxmlLoader.setController(this); try { fxmlLoader.load(); } catch( IOException e ) { throw new RuntimeException(e); } } public void setModel(Model model) { label_rootFolder.textProperty().unbind(); this.model = model; // NOT REALLY NEEDED! label_rootFolder.textProperty().bind(model.rootFolderProperty()); }}和
FileList.fxml。这是您自己的
FileListTab.fxml,其根节点
VBox由
fx:root和
type="javafx.scene.layout.VBox"属性替换,而所有其他属性保持相同:
<?import javafx.geometry.*?><?import javafx.scene.control.*?><?import javafx.scene.layout.*?><fx:root xmlns:fx="http://javafx.com/fxml/1" xmlns="http://javafx.com/javafx/2.2" type="javafx.scene.layout.VBox" maxHeight="-Infinity" maxWidth="-Infinity" minHeight="-Infinity" minWidth="-Infinity" prefHeight="400.0" prefWidth="600.0" spacing="15.0"> <children> <HBox spacing="10.0"> <children> <Label minWidth="100.0" text="Root folder:" /> <Label fx:id="label_rootFolder" /> </children> </HBox> <textarea prefHeight="200.0" prefWidth="200.0" /> <HBox spacing="10.0"> <children> <Label minWidth="100.0" text="Found files:" /> <Label fx:id="label_filesFound" /> </children> </HBox> </children> <padding> <Insets bottom="10.0" left="10.0" right="10.0" top="10.0" /> </padding></fx:root>
您
fx:id在
<FileList>上面的组件中注意到了吗?您现在可以将其注入
MainController:
@FXMLprivate FileList fileList;
并传播
setModel()呼叫:
// in MainControllerpublic void setModel(Model model) { this.model = model; this.fileList.setModel(model);}


