JavaFX and maven: NullPointerException: Location is required

As @Absurd-Mind already explained, maven will not copy any resource files (like fxml) which resides under the src directory.

If you want to keep the fxml files besides the java source files, you can use the maven resource plugin to copy them:

<build>
    ...
    <resources>
        <resource>
            <filtering>false</filtering>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.fxml</include>
            </includes>             
        </resource>
    </resources>
    ...
</build>

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"));

Tags:

Java

Maven

Javafx