JavaFX and maven: NullPointerException: Location is required

后端 未结 6 1951
别跟我提以往
别跟我提以往 2020-11-28 07:03

I have been trying to get Maven set up with JavaFX. Even though I was unexperienced with Maven and JavaFX, I didn\'t expect it to be so much of a challenge. My Java knowledg

6条回答
  •  执笔经年
    2020-11-28 07:31

    Make sure that your sample.fxml is in the src/main/resources/ directory (or a subdirectory). Then you can access the file like this:

    Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("sample.fxml"));
    

    Explanation: During the compile phase all resources and classes get copied to target/classes/. So your fxml file resides in this directory and your class in a subdirectory regarding its package name. If you call getClass().getResource("sample.fxml"); the file will be searched relative to the class file which will be this directory: target/classes/sample/.

    Calling .getResource() on the classloader sets the relative search path to target/classes/ and therefore your file gets found.

    P.S. You could also write:

    Parent root = FXMLLoader.load(getClass().getResource("/sample.fxml"));
    

提交回复
热议问题