Java: I do not Understand the Relative Paths - java

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

Related

Intellij Scala/Java add resource folder

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.

Logic.class.getResource("effects\\newball.wav"); returns null

I've got the problem that the following code snip returns null:
System.out.println(Logic.class.getResource("effects\\newball.wav"));
I have a source folder in my project called effects. in this folder there's the referred file. I think there's a syntax error... Because THE FILE IS THERE. I must refer in this way (means with getResource) to my file because I will export it as jar later.
Thank you
Your effect directory should be a direct child of the src dir. Also in which case, you need a / to start the string path. So you would need this
System.out.println(Logic.class.getResource("/effects/newball.wav"));
ProjectRoot
src
effect
newball.wav
What I normally do using an IDE is just create a new package and name it whatever I want the file to be - in your case "effect". It's easier that way.
UPDATE
"I did it exatly so, but it still returns null"
It works fine for me
package stackoverflow;
public class Test {
public static void main(String[] args) {
System.out.println(Test.class.getResource("/effects/stack_reverse.png"));
}
}
Output: file:/C:/Android/workspace/StackOverflow/bin/effects/stack_reverse.png
Resource paths should use forward slashes, regardless of the filesystem on the machine you are using: try "effects/newball.wav"
See http://docs.oracle.com/javase/7/docs/technotes/guides/lang/resources.html (Under "resources, Names, and Contexts -- "The name of a resource is independent of the Java implementation; in particular, the path separator is always a slash (/).")

Error reading image from scala playn

I researched and looked into the PlayN game framework and I liked it a lot. I program in Scala and actually don't know Java but it's not usually a problem since they work together great.
I've set up a basic project in eclipse and imported all the libraries and dependencies. I even translated over the base maven project code. Here's the two files:
Zeitgeist.scala
package iris.zeit.core
import playn.core.PlayN._
import playn.core.Game
import playn.core.Image
import playn.core.ImageLayer
class Zeitgeist extends Game {
override def init (){
var bgImage: Image = assets().getImage("images/bg.png")
var bgLayer: ImageLayer = graphics().createImageLayer(bgImage)
graphics().rootLayer().add(bgLayer)
}
override def paint (alpha: Float){
//painting stuffs
}
override def update(delta: Float){
}
override def updateRate(): Int = {
25
}
}
Main.scala
package iris.zeit.desktop
import playn.core.PlayN
import playn.java.JavaPlatform
import iris.zeit.core.Zeitgeist
object Main {
def main(args: Array[String]){
var platform: JavaPlatform = JavaPlatform.register()
platform.assets().setPathPrefix("resources")
PlayN.run(new Zeitgeist())
}
}
The cool thing is it works! A window comes up perfectly. The only problem is I can't seem to load images. With the above line, "assets().getImage("images/bg.png")" it pops out
Could not load image: resources/images/bg.png [error=java.io.FileNotFoundException: resources/images/bg.png]
I've played around with the location of my resources file to no avail. I was even able to find bg.png myself with java.io.File. Am I doing something wrong? Is there something I'm forgetting?
Looking at the code of JavaAssetsManager, it looks like it is trying to load a resource and not a file. So you should check that your images are actually in the classpath and at the path you give ("resources/images/bp.png")
Alternatively, you can use getRemoteImage and pass a File URL. As you succeeded in using a java.io.File, you can just get the URL with method toUri of File (toUrl is deprecated).
This almost certainly doesn't work because you're doing this:
platform.assets().setPathPrefix("resources")
That means you're saying your source folder looks like this:
src/main/resources/resources/images/bg.png
src/main/resources/resources/images/pea.png
src/main/resources/resources/images
I imagine it actually looks like one of these:
src/main/resources/assets/images/bg.png <-- 'assets' the default prefix
src/main/resources/assets/images/pea.png
src/main/resources/assets/images
or:
src/main/resources/images/bg.png <-- You have failed to put a subfolder prefix in
src/main/resources/images/pea.png
src/main/resources/images
You can either do this, if you have no prefix:
plat.assets().setPathPrefix("")
Or just put your files in the assets sub-folder inside the resources folder.
It's worth noting that the current implementation calls:
getClass().getClassLoader().getResource(...)
Not:
getClass().getResource(...)
The difference is covered elsewhere, but the tldr is that plat.assets.getImage("images/pea.png") will work, but plat.assets.getImage("/images/pea.png") will not.

How do I load a LWUIT theme file into my Java project?

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.

Why does my icon handling code throw a NullPointerException?

I have added an image for my button,but when I run that frame this exception will be thrown .why?please help me.
init:
deps-jar:
compile-single:
run-single:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at javax.swing.ImageIcon.<init>(ImageIcon.java:138)
at ClientGUI.IdAndPasswordFrame.initComponents(IdAndPasswordFrame.java:91)
at ClientGUI.IdAndPasswordFrame.<init>(IdAndPasswordFrame.java:22)
at ClientGUI.IdAndPasswordFrame$4.run(IdAndPasswordFrame.java:200)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:209)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:597)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:273)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:183)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:173)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:168)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:160)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:121)
BUILD SUCCESSFUL (total time: 1 second)
line 138:
public ImageIcon (URL location) {
this(location, location.toExternalForm());
}
line91:
jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/Images/yahoo_1.gif"))); // NOI18N
I use this poor checking (Peter Lang recommended)which is:System.out.println(getClass().getResource("/Images/yahoo_1.gif")); and it returns null,why? please help me.
This means, that getClass().getResource("/Images/yahoo_1.gif") returns null.
JavaDoc states that this happens if
the resource could not be found or the invoker doesn't have adequate privileges to get the resource.
Check if getResource really returns null:
System.out.println(getClass().getResource("/Images/yahoo_1.gif"));
Make sure that your path is correct and that it is in your classpath.
EDIT:
I just tried it with NetBeans. I created the following structure
Source Packages
Images
yahoo_1.gif
and your code worked fine. Is this your structure?
Try to right-click on your application and select Clean and Build.
In order to fix this, the images need to be copied in the bin directory - not in src directory.
Otherwise you will get null all the time on getClass().getResource("image.png").
The path is not null and you can set it as the above - only if you copy the images that you need inside the binary directory, where .class files for your project are located.
This fixed the problem. Let me know if I helped in this.
Ioana
I had the same problem. What worked for me was:
Look into the jar file or in the bin folder(the one with .class files) and see the path of image.
List item
It looks like getClass().getResource("/Images/yahoo_1.gif") returns null i.e. the .gif cannot be found on your classpath. (Images versus images maybe?)
The URL being passed in is null from this line:
getClass().getResource("/Images/yahoo_1.gif")
From the JDK documentation:
[getResource(..) returns] A URL object for reading the resource,
or null if the resource could not be
found or the invoker doesn't have
adequate privileges to get the
resource
Maybe you meant ("Images/yahoo_1.gif") - i.e. relative path not absolute?
private class HandlerClass implements ActionListener{
public void actionperformed(ActionEvent event){
JOptionPane.showMessageDialog(null, String.format("%s", event.getActionCommand()));
}
}
After reviewing some things when trying to add an image I was presented with the same problem that usually occurs in project with maven.
I found a solution that uses the full path to be able to access the image. Also, create a function that returns an icon with the image and automatically scaled according to the dimensions that are sent to it.
Path -> directory where the image is located, width -> width of the icon, heigth-> height of the icon I hope it serves you, this is my first contribution in the community
public Icon getIcon(String ruta, int width, int heigth) {
Image image = (new ImageIcon(ruta)).getImage().getScaledInstance(width, heigth, 0);
Icon mIcono = new javax.swing.ImageIcon(image);
return mIcono;
}

Categories