FXML 文档拒绝导入其他 fxml 文件

FXML Doccument refusing to import other fxml files

我的程序有一个主要的 FXML 文档,其中包含 TabPane。对于每个选项卡,我希望它有自己的控制器和 fxml 文件。当我尝试将外部 fmxl 文件包含到主 fxml 文档中时,我的程序拒绝 运行。这是我的主要 FXML 文档: 这是我的 java 文件

的副本
@Override
public void start(Stage stage) throws Exception {
    FXMLLoader fxml = new FXMLLoader();
    Parent root = fxml.load(getClass().getResource("FXMLDocument.fxml").openStream());

    Scene scene = new Scene(root);
    stage.setScene(scene);
    stage.show();
    FXMLDocumentController fdc = fxml.getController();
}

错误:

Caused by: javafx.fxml.LoadException: Base location is undefined. unknown path:97

此错误是因为您没有设置 FXMLLoaderlocation 属性,而是指定要从中加载 FXML 的 InputStream .我认为 FXMLLoader 必须知道原始 fxml 文件的位置才能解析包含文件的位置。你真的应该只在特殊情况下使用 load(InputStream) 方法:当你从资源以外的源(即应用程序 jar 文件中的文件或资源)加载 fxml 时。

改为使用

FXMLLoader fxml = new FXMLLoader();
fxml.setLocation(getClass().getResource("FXMLDocument.fxml"));
Parent root = fxml.load();

或者,等价地,

FXMLLoader fxml = new FXMLLoader(getClass().getResource("FXMLDocument.fxml"));
Parent root = fxml.load();