JavaFX Location is not set error message [duplicate] - java

This question already has an answer here:
How do I determine the correct path for FXML files, CSS files, Images, and other resources needed by my JavaFX Application?
(1 answer)
Closed 2 years ago.
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.

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

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

I was getting this exception and the "solution" I found was through Netbeans IDE, simply:
Right-click -> "Clean and Build"
Run project again
I don't know WHY this worked, but it did!

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.

FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../view/Main.fxml"));
in my case i just remove ..
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/view/Main.fxml"));

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!

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 :)

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.

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

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

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

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.

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.

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.

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.

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

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

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

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();
}

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"

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"

Related

unable to load a javafx scene

I have a problem with loading a file. I'm trying to load the scene "areaView.fxml" with the following code:
public class View extends Application {
public static void main(String[] args) {
launch(args);
}
#Override
public void start(Stage primaryStage) throws IOException {
FXMLLoader loader = new FXMLLoader(getClass().getResource("/resources/areaView.fxml"));
Parent root = loader.load();
Scene scene = new Scene(root);
primaryStage.setScene(scene);
primaryStage.show();
}}
But when I launch I get an InvocationTargetException..
For information i'm on windows and the absolute path of the file is: C:\Users\pierr\Desktop\Yves\resources\areaView.fxml
It's probably a stupid mistake but I've been stuck on it for quite some time.... I'm almost sure it's related to the "/" but all my attempts to fix it have failed...
Thank you in advance
EDIT :
Here the full stack tace
EDIT n°2
Very strange thing when I test this:
System.out.println(getClass().getResource("").toString());
I get this : file:/C:/Users/pierr/Desktop/Yves/out/production/Yves/view/
When I would have imagined getting this: file:/C:/Users/pierr/Desktop/Yves/
If i move my file to file:/C:/Users/pierr/Desktop/Yves/out/production/Yves/view/ it works but in fact this solution is not satisfactory
By default your resources folder should be under projectName/src/main/resources.
So in your case: C:\Users\pierr\Desktop\Yves\src\main\resources\areaView.fxml.
In such case .getResource("areaView.fxml") should be sufficient.
Just keep in mind that if you move your fxml to a different folder or you call getResource from a different folder than src/main/java you will have to change the relative path that you pass to the method.

Inflating FXML from subdirectory

I have a Launcher class which I want to use to open a new window.
From main in Launcher, I'm calling :
ChatList chatList = new ChatList(communicator);
The constructor of ChatList calls method showChatList() where I try to inflate a FXML document:
private void showChatList() {
try {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("fxml/ChatList.fxml"));
Parent root = (Parent) fxmlLoader.load();
Stage stage = new Stage();
stage.setScene(new Scene(root));
stage.show();
} catch(Exception e) {
e.printStackTrace();
}
}
However I'm getting a java.lang.IllegalStateException: Location is not set. where I'm calling fxmlLoader.load(). My project file structure is as follows:
I've tried putting in an absolute file path to the FXML file but still had no luck.
Can anyone help me understand what the general principle is behind inflating FXMLs in JavaFX (with multiple stages) or point me to a good resource that they've come across.
Cheers.
I know this is an old question, but maybe can help someone .
You have to write all the path of the fxml.
In your case is:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/client/fxml/ChatList.fxml"));
Another example:
Youproject/Src/parentpackage/childpackage/fxmlToGet.fxml
If you want to get the fxml in childpackage you have to write:
FXMLLoader(getClass().getResource("/parentpackage/childpackage/fxmlToGet.fxml"));

JavaFX - opening multiple windows on application startup

There are a couple questions on how to open a new window on pressing a button, but I'd like to open two windows when the application is launched.
My current approach is to put the following code in a new class that functions as the controller of the new window:
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("secondWindow.fxml"));
fxmlLoader.setController(this);
try {
parent = (Parent) fxmlLoader.load();
scene = new Scene(parent, 500, 400);
stage = new Stage(scene);
stage.show();
} catch (IOException e) {
e.printStackTrace();
}
This works great for buttons or event based openings of windows, I am looking for a simultaneous launching of the two windows. Therefore I'd like to launch my second window from the class with the main method.
In this class you can find the first window being launched using this code:
Parent root = FXMLLoader.load(getClass().getResource("FXMLDocument.fxml"));
Scene scene = new Scene(root);
stage.setScene(scene);
stage.show();
Right below I'd like to add code to launch the second window. I tried:
Parent secondRoot = FXMLLoader.load(getClass().getResource("secondWindow.fxml"));
Scene secondScene = new Scene(secondRoot);
Stage secondStage = new Stage();
secondStage.setScene(secondScene);
secondStage.show();
which to my understanding should do it, but it gives the following error:
java.lang.NoSuchMethodException: monopolybank.SecondWindowController.<init>()
at java.lang.Class.getConstructor0(Class.java:2971)
at java.lang.Class.newInstance(Class.java:403)
How can I fix my approach or what are alternatives to get the same result?
Your problem is nothing to do with the number of windows and all to do with a constructor with parameters that you added to the monopolybank.SecondWindowController class that you created => remove the constructor from that class.

How to Pass Values to Window in JavaFX

I am trying to pass a stored preference value to a text box in a settings window that can be opened from a user login window. I am planning to do this by setting the value in the controller prior to open. As you can see, I am also trying to make the settings window a child of the login window. However, I am getting javafx.scene.layout.AnchorPane cannot be cast to javafx.fxml.FXMLLoader for reasons that I don't understand and am completely at a loss as to what to do.
My code for opening the settings window on the press of a button is as follows:
#FXML
void OpenSettingsWindow(ActionEvent event) {
try {
FXMLLoader fxmlLoader = new FXMLLoader();
fxmlLoader = FXMLLoader.load(SettingsWindowController.class
.getResource("Settings.fxml"));
AnchorPane page = (AnchorPane) FXMLLoader.load(SettingsWindowController.class
.getResource("Settings.fxml"));
Scene scene = new Scene(page);
root = new Stage();
root.initModality(Modality.WINDOW_MODAL);
root.initOwner(Main.primaryStage);
root.setScene(scene);
SettingsWindowController controller = fxmlLoader.getController();
String databaseAddressValue = "databaseAddressValue";
controller.setDatabaseAddressValue(Preferences
.systemRoot()
.node("preferences.SystemPreferences")
.get(SystemPreferences.databaseAddress, databaseAddressValue));
root.show();
} catch (Exception e) {
e.printStackTrace();
}
Any advice as to how to fix this is much appreciated.
You are assigning the return value of FXMLLoader.load() to a FXMLLoader reference.
FXMLLoader.load() returns the highest object in you FXML file and that is for sure not a FXMLLoader object.
If you want to use a controller class for event handling and proper intialization you have to set it first and load the FXML in an other way (I assume that the SettingsWindowController is your controller class and has a default constructor):
SettingsWindowController controller = new SettingsWindowController();
FXMLLoader loader = new FXMLLoader(SettingsWindowController.class
.getResource("Settings.fxml"));
loader.setController(controller);
AnchorPane page = (AnchorPane)loader.load();
Try this :
FXMLLoader fxmlLoader = FXMLLoader(SettingsWindowController.class.getResource("Settings.fxml"));
AnchorPane page = (AnchorPane) fxmlLoader.load();

Reloading an Already Populated AnchorPane

So I have been working on a JavaFX project where I have a pretty simple work flow. I have several different AnchorPanes that I use, on each the user will fill out some information and go on to the next AnchorPane. Whenever they move on to the next AnchorPane I load the new AnchorPane using the following code.
private Initializable replaceSceneContent(String fxml) throws Exception {
FXMLLoader loader = new FXMLLoader();
InputStream in = MyClass.class.getResourceAsStream(fxml);
loader.setBuilderFactory(new JavaFXBuilderFactory());
loader.setLocation(Caster.class.getResource(fxml));
AnchorPane page;
try {
page = (AnchorPane) loader.load(in);
} finally {
in.close();
}
Scene scene = new Scene(page, APP_WIDTH, APP_HEIGHT);
stage.setScene(scene);
stage.sizeToScene();
return (Initializable) loader.getController();
}
This loads everything fine. But I also have the ability to go back to the previous AnchorPane. Currently this uses the same method, but this is not ideal as it loads a brand new AnchorPane and all the information that user had previously entered is gone. I would like to persist the anchorpanes and reload them and have tried to reload them using code similar to the following
private void replaceSceneContent(AnchorPane page) throws Exception {
Scene scene = new Scene(page, APP_WIDTH, APP_HEIGHT);
stage.setScene(scene);
stage.sizeToScene();
}
However, this results in a totally white screen on my application, maybe because I am not loading the FXML again? I need some ideas on how to persist the data the users entered if they want to go back. Any ideas on how to do this well?

Categories