We're writing an Java application using JavaFX. At this time we have 3 different forms:
Login
Game window
Registration
For our next iteration, we want to implement the Registration form, but we get the IOException error Unknown Path
It's about this piece of code:
FXMLLoader registrationLoader = new FXMLLoader();
try{
mainroot = (Parent)registrationLoader.load(this.getClass().getResource("FXMLRegistration.fxml").openStream());
Stage registrationStage = new Stage();
Scene scene = new Scene(mainroot);
registrationStage.setScene(scene);
registrationStage.setTitle("Register your account");
registrationStage.show();
} catch(IOException ex)
{
System.out.print(ex.getMessage());
}
The above code is working when I change FXMLRegistration.fxml to FXMLDocument.fxml or FXMLLoader.fxml.
When I change
mainroot = (Parent)registrationLoader.load(this.getClass().getResource("FXMLRegistration.fxml").openStream());
to
mainroot = (Parent)registrationLoader.load(Paths.get("src/hackattackfx/FXMLRegistration.fxml").toUri().toURL());
source
I get the absolute path in the debugger output, which is correct when I use it with the file command in terminal.
I hope someone could help us with this error.
Thanks in advance!
EDIT
I Changed some code to the following:
FXMLLoader registrationLoader = new FXMLLoader(getClass().getResource("/FXMLRegistration.fxml"));
mainroot = (Parent)registrationLoader.load();
but this will return an IllegalStateException: Location is not set.
When I remove / before /FXMLRegistration.fxml, I get to my catch block printing the full path of the file:
file:/Users/juleskreutzer/Documents/github/PTS3/HackAttackFX/dist/run1793658053/HackAttackFX.jar!/hackattackfx/FXMLRegistration.fxml
Also changing the path to src/hackattackfx/FXMLRegistration.fxml will give the IllegalStateException: Location not set.
Project Structure
We use different packages in our application. all these packages are within the default package: hackattackfx
The packages in the default package are:
Default Package
Exceptions
Interfaces
enums
Resources
Templates
JSON Package
My FXML documents are located in the default package (hackattackfx). If it's not 100% clear how I arranged my files, please take a look at my Github repo
So, I got all curious to find out the root cause, I cloned the repo and found that the actual issue was the following error and the one that was posted by the OP in the question
Caused by: java.lang.NullPointerException
at hackattackfx.FXMLRegistrationController.initialize(FXMLRegistrationController.java:67)
Which means that in the controller pane was null.
This was because the fxml was missing a declaration of fx:id .
Add fx:id="pane" to the AnchorPane declaration of FXMLRegistration.fxml and things should just work fine.
You need to start your Path with /
this is working for me:
final String fxmlPath = "/fxml/Main.fxml";
final FXMLLoader loader = new FXMLLoader(this.getClass().getResource(fxmlPath));
Main.fxml is located in the resource folder (for me: /src/main/resources/fxml/)
Related
I've got following maven project structure as also seen in here (ProjectStructure) :
-maws20.algorithm
|-src/main/resources
|-images
|-menuBanner
|-linearSearchMenuBannerUnsorted.png
|-src/main/java
|-linearSearch.menu
|-LinearSearchMenuBanner.java
I am trying to load that .png image inside of the LinearSearchMenuBanner.java-File with the following Line:
#Override
public Image loadBackgroundImage() {
return new Image(LinearSearchMenuBanner.class.
getResource("/images/menuBanner/linearSearchMenuBannerUnsorted.png").toString());
}
Is this not the correct relative path? Because I get the following error:
...
Caused by: java.lang.NullPointerException: Cannot invoke "java.net.URL.toString()" because the return value of "java.lang.Class.getResource(String)" is null
at linearSearch.menu.LinearSearchMenuBanner.loadBackgroundImage(LinearSearchMenuBanner.java:20)
...
(Line 20 is the line shown above)
I thought I understood the relative paths in Java. ^^'
Thank you for any help.
Remove the first back slash /, which actually means absolute path not the relative path.
Try this:
#Override
public Image loadBackgroundImage() {
File resource = new ClassPathResource("images/menuBanner/linearSearchMenuBannerUnsorted.png").getFile();
return new Image(new String(Files.readAllBytes(resource.toPath()));
}
To know more, you can visit this link: spring-classpath-file-access
Thanks for all your help. I don't know what went wrong, but when i create a completly new Workspace after that create all files new and copy the source code to the new files. Then it works fine.
I dont know why...
But thank you very much :)
I guess this is related to your packaging. The image needs to be on the servers file system, the JAR resources will not work!
ClassPathResource
Supports resolution as java.io.File if the class path resource resides in the file system, but not for resources in a JAR. Always supports resolution as URL.
You are in package search.menu and you need to access the file resource in images/menuBanner So you need to load a resource:
new ClassPathResource(“../../images/menuBanner/linearSearchMenuBannerUnsorted.png
“, LinearSearchMenuBanner
.class).getFile();
Hava a look into other options here:
https://www.baeldung.com/spring-classpath-file-access
I wrote a program which works fine when running it in IntelliJ.
I created artifact, so I can also run it from executable jar, but it doesn't work.
GUI of my app simply does not appear. I run the jar from command line and I got IllegalStateException: Location is not set which is probably caused by this class:
public class SingleIcon extends AnchorPane {
public SingleIcon() {
System.out.println(getClass().getResource("../resources/fxml/SingleIcon.fxml"));
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("../resources/fxml/SingleIcon.fxml"));
fxmlLoader.setRoot(this);
fxmlLoader.setController(this);
try {
fxmlLoader.load();
} catch (IOException exception) {
throw new RuntimeException(exception);
}
}
#FXML private void initialize() {}
}
SingleIcon is created multiple times during initialization of the program.
The System.out.println() line gives me this line numerous times:
file:/C:/Users/Patryk/IdeaProjects/Battleships/out/production/Battleships/battleships/resources/fxml/SingleIcon.fxml
Running jar (java -jar app.jar) from command line gives me null and IllegalStateException.
I checked path I pass to getResource() method and it is correct - I have to get back by one directory and then go through to SingleIcon.fxml. Anyway, it wouldn't work in IntelliJ if the path was not correct.
Do you have any ideas?
You are using a relative path in your call to getResource. This is returning null which is causing the exception. If the resources are packaged with the jar simply call it like this
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/resources/fxml/SingleIcon.fxml"));
Notice the preceding forward slash.
My project-structure:
-Project
--res
---test.jpg
---bla.xml
--src
---Main.scala
Now I want to load bla.xml in my Main.scala
object Main
{
val test = getClass.getResource("res/bla.xml")
}
Throws an IOException right into my face. Now how can I add the res-folder to the projects-searchpath?
I've already marked it as "resource folder".
If I place bla.xml at the root and load it with "bla.xml" everything is just fine, so I'm wondering how to do this in Intellij.
edit: Sascha Kolberg had it right:
Just use val test = getClass.getResource("/bla.xml") if you've added res as an resourcefolder.
My comment as answer:
afaik, all contents or resource folders are placed in the class path root. So just try
val test = getClass.getResource("/bla.xml")
Try val test = getClass.getResource("[full_path_to_bla.xml]"). If this works, slightly adjust, then you will figure out the correct relative path.
Please update us the correct one when you found it.
I'm working on a project that involves loading up a ResourceBundle. More explicitly, I've created a class that extends ListResourceBundle. The class is called Resources.java. It compiles fine and everything, but the MissingResourceException keeps popping up every time I try to load up the class:
All my source files are in package chapter31. When making this call with or without the "chapter31" in the string, always results in a MissingResourceException. My IDE is Eclipse. I've been playing around with this one problem for two days. I even tried changing the version of Eclipse. I'm at the end of my rope. What can I do in Eclipse to ensure that the getBundle() method can see the class. I don't know how it can miss it. It's in the same package! Please advise.
Alikas
package chapter31;
import java.applet.Applet;
import java.applet.AudioClip;
import java.util.ListResourceBundle;
import java.util.ResourceBundle;
import javax.swing.ImageIcon;
public class Resources extends ListResourceBundle {
Object contents[][];
public Resources() {
AudioClip clip = Applet.newAudioClip(getClass().getResource("/E31_10/audio/us.mid"));
ImageIcon image = new ImageIcon(getClass().getResource("/E31_10/image/us.gif"));
contents = new Object[3][2];
contents[0] = new Object[] {"clip", clip};
contents[1] = new Object[] {"icon", image};
contents[3] = new Object[] {"delay", new Integer(68000)};
}
protected Object[][] getContents() {
return contents;
}
public static void main(String[] args) {
ResourceBundle res = ResourceBundle.getBundle("chapter31.Resources");
}
}
The MissingResourceException is misleading here. Your problem may be caused by two other problems:
The resources in the following two lines cannot be found:
AudioClip clip =
Applet.newAudioClip(getClass().getResource("/E31_10/audio/us.mid"));
ImageIcon image = new ImageIcon(getClass().getResource("/E31_10/image/us.gif"));
If the first one is not the problem, there is a second problem:
You have a wrong array index contents[3] which will cause ArrayIndexOutOfBoundsException and this will also cause the misleading MissingResourceException to be thrown. If you can find this exception in your exception stack trace, your problem is here. Change it to contents[2] will solve the problem.
Note: The reason you are seeing MissingResourceException is ultimately caused by the class loader cannot create an instance of the Resources class due to the problems pointed out above. If you had put the contents array initialization codes in a separate method instead of the constructor, you may not get this exception at the object initialization phase. Of course, other exceptions will pop out later when you try to call getObject method.
Are you trying to load a message properties file called "chapter31.Resources"? If so then in Eclipse you can try the below:
Click on "Debug Configuration..."
Find the launcher you are using to execute the main method for Resources
Click on the Classpath tab
Click on "User Entries" and then Click the "Advanced" button
Select "Add External Folder" and choose the folder the "chapter31.Resources" .
ResourceBundle.getBundle() method is looking for the file in your classpath . if this file is not in your classpath it won't be able to find it.
The steps above adds the folder that "chapter31.Resources" to your classpath.
If this still does not work you can try passing the full path of the file to ResourceBundle.getResource().
I am relatively new to Java, so bear with me.
I am completing a tutorial on LWUIT, and just want to load a simple theme, created using the editor. Here is the code in question:
try
{
Container container = c.getContainer();
container.setVisible(true);
Display.init(container);
Display.getInstance().setPureTouch(true);
//Resources r = Resources.open(getClass().getResourceAsStream("/res/Theme.res"));
Resources r = Resources.open("/res/Theme.res");
UIManager.getInstance().setThemeProps(r.getTheme("Simple"));
}
When I use the first (commented out) statement, I get
*** Signal: alarm { "name":"XletException", "domain":"ams", "appId":"com.thomasdge.xlet.hellojamaica.HelloJamaica", "msg":"XletAction['initXlet'] resulted in exception com.aicas.xlet.manager.AMSError: running xlet code caused java exception: initXlet() resulted in exception: java.lang.NullPointerException: <null>.read()I", "data":{ } }
When I use the other, I get
java.io.IOException: /res/Theme.res not found
I have my Theme.res file in /res/Theme. I have also tried it directly in the root, as well as /src. Same results for each.
Any ideas?
If you put the res file in that folder, you will need to go down one level. I recommend you to put the res in the src folder. So, /src/Theme.res. In the code you will only need to write Resources r = Resources.open("/Theme.res");
If resource file placed in res folder, you need to add res folder in project properties. Also you mentioned, the problem even in /src folder, I feel you didn't change the path. Just use Resources.open("/Theme.res") when you use /src folder. Also check the theme name. This should work.