64

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?

Gremash
  • 8,158
  • 6
  • 30
  • 44
  • Where is mainStyles.css? Is it also in the same path location as your FXML and Main application class are? – jewelsea Dec 10 '13 at 23:57
  • 1
    Yes. And that isn't my issue. If I delete the stylesheet info from my xml file it still does not run. That is the first thing I thought might be the issue so I tested it with no stylesheet. – Gremash Dec 11 '13 at 00:12
  • 2
    So in a maven env your fxml has to go to main/resources else it will to get part of your runtime class path. Check what you get from getResource("main.fxml) i think you get null from it! – tomsontom Dec 11 '13 at 05:37

19 Answers19

95

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")
Amir Arad
  • 6,724
  • 9
  • 42
  • 49
  • 1
    This solved it for me, too. Anybody know why getClassLoader() makes a difference? – Phillip Feb 21 '16 at 19:03
  • 4
    If you are using an IDE, the problem may be that the IDE does not know that it needs to copy the .fxml file into the output directory alongside the class files during a build, which is where getClass().getResource() will look for it (it won't look in your source tree!). For instance, if you are using IntelliJ, you may need to add something like ";?.fxml;?.css" to your File|Settings|Compiler settings to tell it to copy the files during a build. See https://stackoverflow.com/questions/23421325/how-to-convert-a-normal-java-project-in-intellij-into-a-javafx-project for more information. – Some Guy Apr 10 '18 at 23:26
  • Thanks, this solved similar issue for me. I was creating URL in JavaFX to dynamically load FXML files. Tried all manner of intelliJ configurations and this simple solution is all I need. – B. Bulpett Jun 27 '21 at 16:23
53

Moving the file to the main/resources directory worked.

Gremash
  • 8,158
  • 6
  • 30
  • 44
  • 15
    I also had to use `Parent root = FXMLLoader.load(getClass().getResource("/fxml/Scene.fxml"));`. – OldCurmudgeon Apr 09 '14 at 15:22
  • 3
    @OldCurmudgeon's comment was crucial as for it to work, it was required to move the `.fxml` file to `resources/fxml` folder. Create the `fxml` folder if it doesn't exist already. – rexxar Jan 25 '17 at 14:01
  • 3
    every time I start a new project I have to come back to this post and it's first comment that works and saves my sanity. and yes, `resources/fxml/Scene.fxml` and `.getResource("/fxml/Scene.fxml")` did the trick, as usual. – rexxar Jul 18 '17 at 17:56
  • Hi. I'm having a similar issue, but I can't manage to solve it. I've asked a question here and maybe someone can help me out. I've also tried to create the /fxml folder as you said: https://stackoverflow.com/questions/47939908/intellij-idea-javafx-class-getresource-returns-null?noredirect=1#comment82849766_47939908 – Davide3i Dec 22 '17 at 13:21
  • Actually, I had a similar problem when I put fxml outside src directory and then it stopped compile. Moving inside src directory (in any subdir you like) will work if you specify relative path. e.g.: `getClass().getResource("../../../resources/layouts/main.fxml")` – Marcos Rocha Apr 24 '20 at 01:13
  • 1
    as suggested if it is in resources it will work by adding a slash before it "/file.fxml", but I wanted to add one thing as I included in my project module-info.java file in which I specificy the packages to open and the imports from the full dependencies. When I deleted that file this slash and resoruces folder technique didn't work. You have to have that module file in order for it to work again. – Mour_Ka Oct 08 '20 at 07:43
34
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;

GreenROBO
  • 4,725
  • 4
  • 23
  • 43
Adeptius
  • 598
  • 5
  • 7
  • 2
    toURL() medthod is depricated. – Gherbi Hicham Mar 26 '17 at 21:11
  • I have exactly the same error and can't figure why it works only like this.... I though the problem came from the *.fxml file not being copied to the out directory, but apparently it works also without ^^ – Fabio Jun 08 '17 at 15:01
  • 3
    Correct the solution. Now toURL is deprecated, then become: (path).toURI().toURL(); – Ospite Jun 12 '17 at 13:18
  • Thx man I really tried everything and this finally seem to work. – Marco Jan 30 '18 at 13:28
  • another way you can try getClass().getClassLoader().getResource(); Or i use now FXMLLoader loader = new FXMLLoader(Gui.class.getResource("../../CrudService.fxml")); "../" - it means parent folder – Adeptius Jan 31 '18 at 13:50
  • Trying to migrate JavaFx 8 to Java 16 mudular and i this problem with maven. I guess that's why JavaFx is not popular you have to debug forever, its a shame all this effort gets wasted. – firephil Apr 13 '21 at 16:44
25

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:

Community
  • 1
  • 1
will
  • 4,799
  • 8
  • 54
  • 90
18

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 .

minigeek
  • 2,766
  • 1
  • 25
  • 35
7

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

james.garriss
  • 12,959
  • 7
  • 83
  • 96
5

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")
alexkov
  • 435
  • 2
  • 7
  • 13
  • This is more a comment on [gronostaj's answer](http://stackoverflow.com/a/31533288/3982001) than an answer to the original question. – Fabio says Reinstate Monica Oct 06 '16 at 21:45
  • Oh, I apologize, I cannot post comments to someone's answers, but maybe it help some newbie like me. But anyway thanks for clarifying, it's true. – alexkov Oct 07 '16 at 08:43
  • 2
    I would avoid using the `..` because deployed builds tend to not know how to work with that pathing symbol. Instead, I do an absolute path. – Lucas Sep 01 '17 at 13:19
3

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")
gronostaj
  • 2,231
  • 2
  • 23
  • 43
2

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.

Evaldas Ilginis
  • 502
  • 4
  • 9
2

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.

mroesler
  • 98
  • 6
  • It solved my problem .There seems to be a security issue related to the fxml file. If you build and run well as a jar file, do not run in a webstart or browser, try this method. – golden_truth May 31 '17 at 10:59
2

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

Thomas Bratt
  • 48,038
  • 36
  • 121
  • 139
1

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!
John Smith
  • 752
  • 9
  • 35
1

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()
PaulNUK
  • 4,774
  • 2
  • 30
  • 58
gigili
  • 195
  • 1
  • 13
1

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.

Noor Hossain
  • 1,620
  • 1
  • 18
  • 25
0

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.

Pedro Borges
  • 1,568
  • 1
  • 14
  • 25
0

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.

budo
  • 74
  • 3
0

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();
    }
}
parsecer
  • 4,758
  • 13
  • 71
  • 140
0

to me , i make mistake, my extension file is .fxml not .xml

so it is nullpointer

 java.lang.NullPointerException: Location is required.
    at javafx.fxml/javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:3361)

Long tran
  • 71
  • 1
  • 2
-1

You should use getClassLoader() method in your root

Parent root = FXMLLoader.load(getClass().getClassLoader().getResource("main.fxml"));
Brahim SLIMANI
  • 310
  • 1
  • 8