JavaFX "Location is required." even though it is in the same package

JavaJavafx 2

Java Problem Overview


I am trying to get my JavaFX program to run but am having some difficulty. I keep getting an error of 'java.lang.NullPointerException: Location is required.' The fxml file is in the same package as Application class. Here is my very simple code:

package com.kromalights.designer.entry;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{
        Parent root = FXMLLoader.load(getClass().getResource("main.fxml"));
        primaryStage.setTitle("Kromalights Designer");
        primaryStage.setScene(new Scene(root, 300, 275));
        primaryStage.show();
    }


    public static void main(String[] args) {
        launch(args);
    }
}

And here is a copy of my main.fxml file:

<?xml version="1.0" encoding="UTF-8"?>

<?import java.lang.*?>
<?import javafx.scene.layout.*?>
<?import javafx.scene.layout.BorderPane?>
<?scenebuilder-stylesheet mailStyles.css?>
<?import java.net.*?>

<BorderPane prefHeight="300.0" prefWidth="300.0" xmlns:fx="http://javafx.com/fxml/1"
        xmlns="http://javafx.com/javafx/2.2"
        fx:controller="com.kromalights.designer.entry.Controller">
    <bottom>
        <Pane prefHeight="200.0" prefWidth="200.0"/>
    </bottom>
    <center>
        <Pane prefHeight="200.0" prefWidth="200.0"/>
    </center>
    <left>
        <VBox prefHeight="200.0" prefWidth="100.0"/>
    </left>
    <top>
        <HBox prefHeight="100.0" prefWidth="200.0"/>
    </top>
    <stylesheets>
        <URL value="@mainStyles.css" />
    </stylesheets>
</BorderPane>

The controller class does exist and is in the package specified in the fxml file. All of my names are correct and are where I think they should be. What am I missing? I did try renaming my fxml file in case it was a name issue. Please help. FYI, I am using Intellij IDEA on OSX.

UPDATE: This is a Maven issue. I setup Maven for this project and that caused the issue. I removed Maven temporarily so I can continue working without it. Does anyone have any insight as to how I would best handle this when using Maven?

Java Solutions


Solution 1 - Java

In my case all of the above were not the problem at all.

My problem was solved when I replaced :

getClass().getResource("ui_layout.fxml")

with :

getClass().getClassLoader().getResource("ui_layout.fxml")

Solution 2 - Java

Moving the file to the main/resources directory worked.

Solution 3 - Java

URL url = new File("src/main/java/ua/adeptius/goit/sample.fxml").toURI().toURL();
Parent root = FXMLLoader.load(url);

That is helped for me because

getClass.getResource("path")

always returns me null;

Solution 4 - Java

I've seen this error a few times now. So often that I wrote a small project, called "Simple" with a Netbeans Maven FXML application template just to go back to as a kind of 'reference model' when things go askew. For testing, I use something like this:

    String sceneFile = "/fxml/main.fxml";
    Parent root = null;
    URL    url  = null;
    try
    {
        url  = getClass().getResource( sceneFile );
        root = FXMLLoader.load( url );
        System.out.println( "  fxmlResource = " + sceneFile );
    }
    catch ( Exception ex )
    {
        System.out.println( "Exception on FXMLLoader.load()" );
        System.out.println( "  * url: " + url );
        System.out.println( "  * " + ex );
        System.out.println( "    ----------------------------------------\n" );
        throw ex;
    }

When you run that snippet and the load fails, you should see a reason, or at least a message from the FXMLLoader. Since it's a test, I throw the exception. You don't want to continue.

Things to note. This is a maven project so the resources will be relative to the resources folder, hence:

  • "/fxml/main.fxml".

  • The leading slash is required.

  • The resource passed to the FXMLLoader is case-sensitive:

     // If you load "main.fxml" and your file is called: "Main.fxml"
     // You will will see the message ...
    
     java.lang.NullPointerException: Location is required.
    
  • If you get past that "location is required" issue, then you may have a problem in the FXML

    // Something like this:
    //
    javafx.fxml.LoadException: 
      file:/D:/sandbox/javafx/app_examples/person/target/person-00.00.01-SNAPSHOT.jar!/fxml/tableWithDetails.fxml:13
    

Will mean that there's a problem on Line 13, in the file, per:

  • tableWithDetails.fxml :13

In the message. At this point you need to read the FXML and see if you can spot the problem. You could try some of the tips in the related question.

For this problem, my opinion is that the file name was proper case: "Main.fxml". When the file was moved the name was probably changed or the string retyped. Good luck.

Related:

Solution 5 - Java

instead of

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

put

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

Difference is of " / " .

Reason :

1st one : getResource will try to find the resource relative to the package

2nd one : getResource will treat it as an absolute path and simply call the classloader .

Solution 6 - Java

I couldn't use

getClass().getResource("views/view.fxml")

because I put my controller class into "controllers" package, so here is my solution:

getClass().getResource("../views/view.fxml")

Solution 7 - Java

If you look at the docs [1], you see that the load() method can take a URL:

load(URL location)

So if you're running Java 7 or newer, you can load the FXML file like this:

URL url = Paths.get("./src/main/resources/fxml/Fxml.fxml").toUri().toURL();
Parent root = FXMLLoder.load(url);

This example is from a Maven project, which is why the FXML file is in the resources folder.

[1] https://docs.oracle.com/javase/8/javafx/api/javafx/fxml/FXMLLoader.html

Solution 8 - Java

This problem can be caused by incorrect path to the FXML file.

If you're using absolute paths (my/package/views/view.fxml), you have to precede then with a slash:

getClass().getResource("/my/package/views/view.fxml")

You can use relative paths as well:

getClass().getResource("views/view.fxml")

Solution 9 - Java

I was getting the same error. In my case there was a leading space-symbol in the fxml file name:

" fxml_example.fxml" instead of "fxml_example.fxml"

I don't know where it came from. It was very difficult to notice it. When I removed the leading space, everything went ok. I didn't even knew that file name could start with the space-symbol.

Solution 10 - Java

If your problem is not Maven related and you get the same NullPointerException running this in a browser (while running it from the IDE is fine), try this:

> -> Netbeans -> Right-Click Project -> Properties -> Build -> Deployment -> Check "Request unrestricted access (Enable signing, > self-signed)" > > This is due to the @FXML Annotation needing permission to inject the > value from the FXML markup (see > http://docs.oracle.com/javafx/2/fxml_get_started/fxml_deployment.htm )

I was running my App on JDK8u31 and it would never run without the certificate in Chrome / Firefox / IE.

Solution 11 - Java

The root directory for the loader is in the 'resources' folder for a maven project. So if you have src/main/java then the fxml file path should start from: src/main/resources

https://maven.apache.org/guides/introduction/introduction-to-the-standard-directory-layout.html

Solution 12 - Java

I have found all of the above solutions work just fine because they trigger your IDE to rebuild the project. No magic involved.

The "real" solution for this issue is that you should just ditch your previous build directory.

  • If you are using Maven, just delete the target folder (or do a mvn clean)!
  • If you're using ANT, delete that respective folder (I think it's called out)!
  • If you're using Gradle, delete the build folder!

Solution 13 - Java

I tried above answers and it didn't work in my project. My project was with maven and openjfx in Windows.

This solved the problem :

FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader.setLocation(getClass().getResource("/main.fxml"));
root = fxmlLoader.load()

Solution 14 - Java

June/2021:

After Converting the Project To Maven You Should move fxml and css file to resource folder. Just Drag and Drop (in IntelliJ Community). Then :

Parent root = FXMLLoader.load(Objects.requireNonNull(getClass().getClassLoader().getResource("FXMLDocument.fxml")));

and :

 root.getStylesheets().add(getClass().getResource("/newCascadeStyleSheet.css").toString());
    

A Slash is require for the styleSheet.

Thats All.

Solution 15 - Java

If your project is Maven based Idea will ignore all but java files in your src/main/java folder. Like you said moving the file to src/main/resources works, but now SceneBuilder does not know about your controller class anymore because it's in a completely different directory and you lose all the insight, you build blindly.

I believe this is an issue in intellij since SceneBuilder EXPECTS to find your controller class java file in (and i quote) "the same directory, a direct subdirectory or the parent directory of the .fxml" document.

Solution 16 - Java

I had sometimes the same Exception.

When i create a FXML-File with the Wizard in Eclipse, i write example.fxml in the name field. Eclipse creates a file, like example.fxml.fxml. With this mistake, the FXMLLoader can't find the right FXML-File. So, my tip, check the name of the FXML-Filename in your start-Method and the real Name of File.

Hopes i could help. Good luck.

Solution 17 - Java

I had structure like this:

src
  main
    java
      dogapp
        DogApp.java (the class that contains the main method and overloaded start method)
    resources
      DogApp.fxml

but it needed to be like this (needed to have the dogapp folder inside resources folder):

src
  main
    java
      dogapp
        DogApp.java (the class that contains the main method and overloaded start method)
    resources
      dogapp
        DogApp.fxml

DogApp.java:

public class DogApp extends Application {
    public static void main(String[] args) {
        Application.launch(args);
    }
    
    @Override
    public void start(Stage primaryStage) throws IOException  {
        primaryStage.setTitle("Dog App");
        primaryStage.setScene(new Scene(FXMLLoader
                .load(getClass().getResource("DogApp.fxml"))));
        primaryStage.show();
    }
}

Solution 18 - Java

You should use getClassLoader() method in your root

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionGremashView Question on Stackoverflow
Solution 1 - JavaAmir AradView Answer on Stackoverflow
Solution 2 - JavaGremashView Answer on Stackoverflow
Solution 3 - JavaAdeptiusView Answer on Stackoverflow
Solution 4 - JavawillView Answer on Stackoverflow
Solution 5 - JavaminigeekView Answer on Stackoverflow
Solution 6 - JavaalexkovView Answer on Stackoverflow
Solution 7 - Javajames.garrissView Answer on Stackoverflow
Solution 8 - JavagronostajView Answer on Stackoverflow
Solution 9 - JavaEvaldas IlginisView Answer on Stackoverflow
Solution 10 - JavamroeslerView Answer on Stackoverflow
Solution 11 - JavaThomas BrattView Answer on Stackoverflow
Solution 12 - JavaJohn SmithView Answer on Stackoverflow
Solution 13 - JavagigiliView Answer on Stackoverflow
Solution 14 - JavaNoor HossainView Answer on Stackoverflow
Solution 15 - JavaPedro BorgesView Answer on Stackoverflow
Solution 16 - JavabudoView Answer on Stackoverflow
Solution 17 - JavaparsecerView Answer on Stackoverflow
Solution 18 - JavaBrahim SLIMANIView Answer on Stackoverflow