JavaFX Location is not set error message [duplicate]
Asked Answered
N

21

70

I have problem when trying to close current scene and open up another scene when menuItem is selected. My main stage is coded as below:

public void start(Stage primaryStage) throws Exception {
    primaryStage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("cartHomePage.fxml"));

    Pane myPane = (Pane) myLoader.load();

    CartHomePageUI controller = (CartHomePageUI) myLoader.getController();

    controller.setPrevStage(primaryStage);
    Scene myScene = new Scene(myPane);
    primaryStage.setScene(myScene);
    primaryStage.show();
}

When the program is executed, it will go to the cartHomePage.fxml. From there, I can select to go to create product or create category when the menu item is selected. Here is my action event:

Stage prevStage;

public void setPrevStage(Stage stage){
     this.prevStage = stage;
}

 public void gotoCreateCategory(ActionEvent event) throws IOException {
  Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("createCategory.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();       
}

//Method to change scene when menu item create product is on click
@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
   Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(getClass().getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();      
}

However, I can only switch the stage once. For example, my default page is cartHomePage.fxml. When I run the program, first I go to create product stage. After that, I cannot go to anywhere any more. The error message is:

java.lang.IllegalStateException: Location is not set.
and Null Pointer Exception

I did set the stage after I close it and pass it around. I wonder which part went wrong.

Thanks in advance.

Nertie answered 21/6, 2013 at 5:49 Comment(0)
M
60

I had this problem and found this post. My issue was just a file name issue.

FXMLLoader(getClass().getResource("/com/companyname/reports/" +
report.getClass().getCanonicalName().substring(18).replaceAll("Controller", "") +
".fxml"));

Parent root = (Parent) loader.load();

I have an xml that this is all coming from and I have made sure that my class is the same as the fxml file less the word controller.

I messed up the substring so the path was wrong...sure enough after I fixed the file name it worked.

To make a long story short I think that the problem is either the filename is named improperly or the path is wrong.

ADDITION: I have since moved to a Maven Project. The non Maven way is to have everything inside of your project path. The Maven way which was listed in the answer below was a bit frustrating at the start but I made a change to my code as follows:

FXMLLoader loader = new FXMLLoader(ReportMenu.this.getClass().getResource("/fxml/" + report.getClass().getCanonicalName().substring(18).replaceAll("Controller", "") + ".fxml"));
Morrow answered 6/3, 2014 at 20:25 Comment(4)
I like it when the error message has nothing to do with the problem ;) EDIT: the helper could be more generic: FXMLLoader(getClass().getResource("/" + report.getClass().getCanonicalName().replaceAll(".","/").replaceAll("Controller", "") + ".fxml"));Monzonite
@DoctorHenry Thanks. I am still trying to completely understand FX...every day is a new struggle.Morrow
@Morrow You're welcome. I am working on a project that has JavaFX and Android version. The android lot more comfortable, easy to use, standard than JavaFX. I'm going to hate JavaFX.Sural
I got this error when I changed to a maven project. I had to move all fxml files to the resource folder.Demagogy
R
37

I know this is a late answer, but I hope to help anyone else who has this problem. I was getting the same error, and found that I had to insert a / in front of my file path. The corrected function call would then be:

FXMLLoader myLoader = new FXMLLoader(getClass().getResource("/createCategory.fxml"));
//                                                           ^
Readiness answered 24/5, 2017 at 23:30 Comment(0)
R
31

I was getting this exception and the "solution" I found was through Netbeans IDE, simply:

  1. Right-click -> "Clean and Build"
  2. Run project again

I don't know WHY this worked, but it did!

Romalda answered 4/1, 2014 at 10:56 Comment(4)
This also was the cause for me. I don't know why, but it fixed it. In Eclipse, I did from the menu: Project -> Clean... and it worked when I pressed run.Eurypterid
Seems like cleaning up project build files does the trick. Works also with greadle clean.Manassas
Ouh that Eclipse and Netbeans ..... made me a crazy developer .... they are full of damn bugs.Ligula
I've been trying to solve the issue for 4 hours straight and this just solved it ! Very weird!Martelli
R
21

I converted a simple NetBeans 8 Java FXML application to the Maven-driven one. Then I got problems, because the getResource() methods weren't able to find the .fxml files. In mine original application the fxmls were scattered through the package tree - each beside its controller class file. After I made Clean and build in NetBeans, I checked the result .jar in the target folder - the .jar didn't contain any fxml at all. All the fxmls were strangely disappeared.

Then I put all fxmls into the resources/fxml folder and set the getResource method parameters accordingly, for example: FXMLLoader(App.class.getClassLoader().getResource("fxml/ObjOverview.fxml")); In this case everything went OK. The fxml folder appeared int the .jar's root and it contained all my fxmls. The program was working as expected.

Ransom answered 24/7, 2014 at 21:38 Comment(3)
yes this works, and in case you do not want to call getClassLoader() it is important to specify the root back slash on the path like FXMLLoader(App.class.getResource("/fxml/ObjOverview.fxml"));Rapper
Saved my day! If u use maven you have to store your fxml files in the resource folder! @Evaldas Illginis has this folder structure: resources/fxml/ObjOverview.fxmlLinell
@Linell Does this folder resources have to be inside src folder? Do you know if this should work in Eclipse as well?Ascendancy
E
8
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/Main.fxml")); 

in my case i just remove ..

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/Main.fxml")); 
Eudemonics answered 6/7, 2018 at 7:17 Comment(1)
In my case I had to do the opposite and prepend ".." to the path.Diamagnetic
M
5

I've had the same issue in my JavaFX Application. Even more weird: In my Windows developement environment everything worked fine with the fxml loader. But when I executed the exact same code on my Debian maschine, I got similar errors with "location not set".

I read all answers here, but none seemed to really "solve" the problem. My solution was easy and I hope it helps some of you:

Maybe Java gets confused, by the getClass() method. If something runs in different threads or your class implements any interfaces, it may come to the point, that a different class than yours is returned by the getClass() method. In this case, your relative path to creatProduct.fxml will be wrong, because your "are" not in the path you think you are...

So to be on the save side: Be more specific and try use the static class field on your Class (Note the YourClassHere.class).

@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
   Stage stage = new Stage();
    stage.setTitle("Shop Management");
    FXMLLoader myLoader = new FXMLLoader(YourClassHere.class.getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
    prevStage.close();
    setPrevStage(stage);
    stage.show();      
}

After realizing this, I will ALWAYS do it like this. Hope that helps!

Manuel answered 8/9, 2015 at 20:46 Comment(1)
I had the same problem in Ubuntu 20.0.4 and have been struggling to find an answer. This, however, worked like a charm!Searcy
M
5

I tried a fast and simple thing:

I have two packages -> app.gui and app.login

In my login class I use the mainview.fxml from app.gui so I did this in the login.fxml

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../gui/MainView.fxml"));

And it works :)

Matey answered 10/11, 2015 at 9:37 Comment(1)
Note that if resources are packaged in a jar file, .. will not resolve them as the jar: protocol does not support the .. parent directory locator.Parthenogenesis
R
3

This is often not getting the location path correct. It is important to realize that the path starts from the current package which the code resides in and not the root of the project. As long as you get this relative path correct, you should be able to steer clear of this error in this case.

Radiotelegraphy answered 1/9, 2014 at 2:6 Comment(1)
Sorry to sound like my mother: But it is also important to realize, that the path starts from the package of the class, which is being returned by the "getClass()" method. This must not neccessarily be the class in which the code is located.Manuel
S
3

I think problem is either incorrect layout name or invalid layout file path.

for IntelliJ, you can create resource directory and place layout files there.

FXMLLoader loader = new FXMLLoader();
loader.setLocation(getClass().getResource("/sample.fxml"));
rootLayout = loader.load();
Schematize answered 7/7, 2017 at 9:11 Comment(0)
A
2

I had the same problem.

after a few minutes, i figured it that i was trying the load the file.fxml from wrong location.

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/[wrong-path]/abc.fxml"));
fxmlLoader.setClassLoader(getClass().getClassLoader());
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
fxmlLoader.load();
Arthralgia answered 21/9, 2015 at 9:38 Comment(0)
C
1

I mean something like this:

FXMLLoader myLoader = null; Scene myScene = null; Stage prevStage = null;

public void start(Stage primaryStage) throws Exception {
  primaryStage.setTitle("Shop Management");
  myLoader = new FXMLLoader(getClass().getResource("cartHomePage.fxml"));
  Pane myPane = (Pane) myLoader.load();
  CartHomePageUI controller = (CartHomePageUI) myLoader.getController();
  controller.setPrevStage(primaryStage);
  myScene = new Scene(myPane);
  primaryStage.setScene(myScene);
  primaryStage.show();
}

After that

public void setPrevStage(Stage stage){
    this.prevStage = stage;
}

public void gotoCreateCategory(ActionEvent event) throws IOException {
    Stage stage = new Stage();
    stage.setTitle("Shop Management");
    myLoader = new FXMLLoader(getClass().getResource("createCategory.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
// prevStage.close(); I don't think you need this, closing it will set preStage to null   put a breakpoint after this to confirm it
    setPrevStage(stage);
    stage.show();       
}

//Method to change scene when menu item create product is on click
@FXML
public void gotoCreateProduct(ActionEvent event) throws IOException {
    Stage stage = new Stage();
    stage.setTitle("Shop Management");
    myLoader = new FXMLLoader(getClass().getResource("creatProduct.fxml"));
    Pane myPane = (Pane) myLoader.load();            
    Scene scene = new Scene(myPane);
    stage.setScene(scene);
// prevStage.close(); I don't think you need this, closing it will set preStage to null put a breakpoint after this to confirm it
    setPrevStage(stage);
    stage.show();      
}

Try it and let me know please.

Capo answered 21/6, 2013 at 8:14 Comment(3)
Yes, it worked without showing error message. But you cancelled out the .close() so the stages will keep stacking without closing. What I am trying to do is like JFrame. You open up a JFrame, choose something then current one will close, and open up another one.Nertie
Oh ok I unterdtand what you are doing :). As I said before, it is more easy if you use Global variables. Add Scene globalScene, to FXMLLoader myLoader = null; Scene myScene = null; Stage prevStage = null; Then you will just have One Scene, whitch you can rotate on, closing and creating anonther one.Capo
Or anyway Add Stage CurrentStage = null, to FXMLLoader myLoader = null; Scene myScene = null; Stage prevStage = null; Then you will just have One Scene, which you can rotate on, closing and creating another one. Now it can be possible to you, to close CurrentStage and create a new one. Let me know if it work for you. LionnelCapo
K
1

The answer below by CsPeitch and others is on the right track. Just make sure that the fxml file is being copied over to your class output target, or the runtime will not see it. Check the generated class file directory and see if the fxml is there

Krissy answered 14/8, 2015 at 20:34 Comment(0)
D
1

For Intellij users, my issue was that the directory where I had my fxml files (src/main/resources), was not marked as a "Resources" directory.

Open up the module/project settings go to the sources tab and ensure that Intellij knows that the directory contains project resource files.

Diaz answered 8/8, 2016 at 18:21 Comment(0)
L
0

That happened to me an i found the solution. If u build your project with your .fxml files in different packages from the class that has the launch line (Parent root = FXMLLoader.load(getClass().getResource("filenamehere.fxml"));) and use a relative path your windows except from the first one wont launch when your run the jar. To keep it short place the .fxml file in the same package with the class that launches it and set the path like this ("filenamehere.fxml") and it should work fine.

Lithoid answered 8/8, 2015 at 13:39 Comment(1)
you should never move a class, just because its more convinient for you! Each and every class has its puropse and that purpose should define, where it should be located in your package.Manuel
O
0

I've stumbled upon the same problem. Program was running great from Eclipse via "Run" button, but NOT from runnable JAR which I'd exported before. My solution was:

1) Move Main class to default package

2) Set other path for Eclipse, and other while running from the JAR file (paste this into Main.java)

public static final String sourcePath = isProgramRunnedFromJar() ? "src/" : "";
public static boolean isProgramRunnedFromJar() {
    File x = getCurrentJarFileLocation();
    if(x.getAbsolutePath().contains("target"+File.separator+"classes")){
        return false;
    } else {
        return true;
    }
}
public static File getCurrentJarFileLocation() {
        try {
            return new File(Main.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());
        } catch(URISyntaxException e){
            e.printStackTrace();
            return null;
        }
}

And after that in start method you have to load files like this:

FXMLLoader loader = new FXMLLoader(getClass().getResource(sourcePath +"MainScene.fxml"));

It works for me in Eclipse Mars with e(fx)clipse plugin.

Odey answered 16/2, 2016 at 18:24 Comment(0)
D
0

mine was strange... IntelliJ specific quirk.

I looked at my output classes and there was a folder:

x.y.z

instead of

x/y/z

but if you have certain options set in IntelliJ, in the navigator they will both look like x.y.z

so check your output folder if you're scratching your head

Dialectology answered 18/3, 2017 at 3:11 Comment(1)
btw. Location not set wins my vote for most useless exception description ever. I guess the JavaFX developers never heard of %s?Dialectology
C
0

I had the same problem. It's a simple problem of not specifying the right path.

Right click on the on your .fxml file and select properties (for those using eclipse won't differ that much for another IDE) and then copy the copy the location starting from /packagename till the end and that should solve the problem

Constrictor answered 10/5, 2017 at 1:6 Comment(0)
B
0

I had the same problem, I changed the FXML name to the FXML file in the controller class and the problem was solved.

Buchner answered 2/1, 2021 at 15:42 Comment(0)
H
0

This worked for me well :

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

    @Override
    public void start(Stage primaryStage) throws IOException {

        FXMLLoader loader = new FXMLLoader(getClass().getResource("/fxml/TestDataGenerator.fxml"));
        loader.setClassLoader(getClass().getClassLoader());
        Parent root = loader.load();
        primaryStage.setScene(new Scene(root));
        primaryStage.show();
    }
Habitation answered 5/2, 2021 at 3:6 Comment(1)
LLoader myLoader = new FXMLLoader(YourProductControlClassHere.class.getResource("creatProduct.fxml")); helped me when calling a sub package .fxml and and using its control class!'Criminology
F
-2

In my case the reason for the error was an runtime error in my corresponding java class. I fixed it and all was ok. My tip: don't search for an "location not set"

Fructify answered 29/8, 2019 at 20:30 Comment(1)
Do you think that is helpful?Ellord
E
-2

I had faced he similar problem however it got resolved once i renamed the file , so i would suggest that you should

"Just rename the file"

Elbertine answered 16/11, 2019 at 11:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.