我建议更改项目结构。资源不应驻留在源本身中。所以我的建议是以下项目结构:
src|-main |-java <-- This should be your 'sources root' |-application <-- The application itself is within the new sources root |-controllers |here are my controllers |-dao |-service |-resources <-- all resources (css files, images, fxml files) should be with a subfolder of the resources. This folder should be marked as 'resources root' |-css |-images |-view |here are the fxml files
可以在任何IDE中设置此结构。如何设置它取决于IDE本身。通常,您只需右键单击概述中的文件夹,然后将其标记为源/资源根。“源根”和“资源根”的确切名称取决于IDE。
在
Main现在是在包装
application和
MainUIController在包
controllers。
在FXML文件中,您应该指定:
fx:controller="controllers.MainUIController"
加载FXML文件应适用于:
AnchorPane root = (AnchorPane) FXMLLoader.load(getClass().getClassLoader().getResource("view/MainUI.fxml"));至于下面的解释参考,看看这里:
将
ClassLoader始终从你的资源的根本。如果仅使用
getClass,则资源的路径是相对路径。在处理了几次之后,我自己决定始终使用绝对路径,因此使用
getClassLoader。
如上面链接中所述,请注意
getClass().getClassLoader().getResource("view/MainUI.fxml");可以替换为
getClass().getResource("view/MainUI.fxml");我认为我在某处阅读过,最好直接使用
InputStreamif(如果可用),因为在JAR-
Files中处理URL有时会很棘手(但我目前找不到支持该引用的参考)。因此,可以替代
getResource(..)使用:
FXMLLoader loader = new FXMLLoader();Parent root = loader.load(getClass().getClassLoader().getResourceAsStream("view/MainUI.fxml");


