简体   繁体   English

即使文件路径正确,也不会加载FXML文件

[英]FXML file won't load even when file path is correct

I am trying to load an FXML file: 我正在尝试加载FXML文件:

URL url = getClass().getClassLoader().getResource("/frontEnd/fxml/ModeScreen.fxml");

try {
    this.value = FXMLLoader.load(url);
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

But when I run, I get: 但是当我跑步时,我得到:

NullPointerException: Location is required

the path to my fxml file is: 我的fxml文件的路径是:

src/frontEnd/fxml/ModeScreen.fxml

and the path to my class file is: 而我的班级文件的路径是:

src/frontEnd/ModeScreen.java

this.value extends AnchorPane and the FXML file's root is an AnchorPane. this.value extends AnchorPane ,FXML文件的根是AnchorPane。

I checked and made sure that all of these files are in the bin folder and it doesn't run in either a jar file or Eclipse 我检查并确保所有这些文件都在bin文件夹中,并且既不在jar文件中也不在Eclipse中运行

I have also tried to use the following paths: 我也尝试使用以下路径:

frontEnd/fxml/ModeScreen.fxml
../frontEnd/fxml/ModeScreen.fxml
src/frontEnd/fxml/ModeScreen.fxml
/src/frontEnd/fxml/ModeScreen.fxml
/fxml/ModeScreen.fxml
fxml/ModeScreen.fxml

I have also tried using getResourceAsStream.toString 我也尝试过使用getResourceAsStream.toString

file structure is as follows: 文件结构如下:

bin

    application

        Main

    frontEnd

        controllers

        fxml<---<all the fxml files are in here. I checked too.>

        ModeScreen.class

There must be some tiny thing I am doing wrong. 我一定做错了一些小事情。

The problem in here is that you are appending a / , when you are already using a ClassLoader 's getResource() . 这里的问题是,当您已经在使用ClassLoadergetResource()时,您将附加一个/

You should never use a / at the beginning of a ClassLoader path is because all ClassLoader paths are absolute . 您绝对不要在ClassLoader路径的开头使用/ ,因为所有ClassLoader paths are absolute

You can definitely use Class 's getResource() with a URL which starts with / , because before it delegates down to the classloader, it creates an absolute URL. 绝对可以将ClassgetResource()与以/开头的URL一起使用,因为在将其委托给类加载器之前,它会创建一个绝对URL。

From the JavaDocs : 从JavaDocs:

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm: 在委派之前,使用以下算法从给定资源名称构造绝对资源名称:

  • If the name begins with a '/' ('\/'), then the absolute name of the resource is the portion of the name following the '/'. 如果名称以'/'('\\ u002f')开头,则资源的绝对名称是名称中'/'之后的部分。

The following are valid url : 以下是有效的网址:

Using ClassLoader : 使用ClassLoader:

URL url = getClass().getClassLoader().getResource("frontEnd/fxml/ModeScreen.fxml");

Using Class : 使用类:

URL url = getClass().getResource("/frontEnd/fxml/ModeScreen.fxml");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM