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