Writing Images to ImageIcon in loop [duplicate] - java

The line
andImg = ImageIO.read(getClass().getResource("gate_and.png"));
fails with
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
I'm using Eclipse and in the navigation view under the bin folder there is the file gate_and.png, suggesting that the file is in the build path.
In the package explorer view I have
project/src/view/class - This is the class that has the code above.
and
project/images/gate_and.png
I right clicked the project folder > build path > link source to add the images folder as a source, doing this again provides a confirmation msg that says images is already in the source.
I have also tried changing gate_and.png to images/gate_and.png and /images/gate_and.png, but since the image gate_and.png is in the bin folder, I think the original is correct.

Assuming your class is in package view.random.name, then
getClass().getResource("gate_and.png")
will look for the resource in
/view/random/name/gate_and.png
relative to the root of the classpath. You apparently don't have a resource by that name there.
By setting project/images as a build path entry, Eclipse will include everything in it on the classpath. Therefore, your resource will appear at
/gate_and.png
You can access it with
getClass().getResource("/gate_and.png")
Note the leading / that means start looking at the root of the classpath, ie. it's an absolute path.
All these rules are explained in the javadoc.

Related

Unable to use images in Intellij IDEA [duplicate]

I have a Java Project in NetBeans 7.0.
I want to add some image to some label dynamically. The image will differ depending on the state of the program.
I put one such image, 'filling.jpg', in the 'resources' folder of my project.
I want to reach this file correctly (not by absolute or relative path, because that will cause problems when I build the jar file).
So I found this method:
ImageIcon fillingIcon = new ImageIcon(getClass().getClassLoader().getResource("filling.jpg"));
labelFontFilling.setIcon(fillingIcon);
It keeps give me java.lang.NullPointerException.
But I am sure that there is that image, because I can assign the image to the label from the NetBeans Properties menu for that label (but I don't want this, I want to add the image by Java code).
What am I doing wrong, and how can I get that image correctly?
This was a pain, using netBeans IDE 7.2.
You need to remember that Netbeans cleans up the Build folder whenever you rebuild, so
Add a resource folder to the src folder:
(project)
src
project package folder (contains .java files)
resources (whatever name you want)
images (optional subfolders)
After the clean/build this structure is propogated into the Build folder:
(project)
build
classes
project package folder (contains generated .class files)
resources (your resources)
images (your optional subfolders)
To access the resources:
dlabel = new JLabel(new ImageIcon(getClass().getClassLoader().getResource("resources/images/logo.png")));
and:
if (common.readFile(getClass().getResourceAsStream("/resources/allwise.ini"), buf).equals("OK")) {
worked for me. Note that in one case there is a leading "/" and in the other there isn't.
So the root of the path to the resources is the "classes" folder within the build folder.
Double click on the executable jar file in the dist folder. The path to the resources still works.
I have a slightly different approach that might be useful/more beneficial to some.
Under your main project folder, create a resource folder. Your folder structure should look something like this.
Project Folder
build
dist
lib
nbproject
resources
src
Go to the properties of your project. You can do this by right clicking on your project in the Projects tab window and selecting Properties in the drop down menu.
Under categories on the left side, select Sources.
In Source Package Folders on the right side, add your resource folder using the Add Folder button. Once you click OK, you should see a Resources folder under your project.
You should now be able to pull resources using this line or similar approach:
MyClass.class.getResource("/main.jpg");
If you were to create a package called Images under the resources folder, you can retrieve the resource like this:
MyClass.class.getResource("/Images/main.jpg");
Thanks, Valter Henrique, with your tip i managed to realise, that i simply entered incorrect path to this image.
In one of my tries i use
String pathToImageSortBy = "resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
But correct way was use name of my project in path to resource
String pathToImageSortBy = "nameOfProject/resources/testDataIcons/filling.png";
ImageIcon SortByIcon = new ImageIcon(getClass().getClassLoader().getResource(pathToImageSortBy));
For me it worked like I had images in icons folder under src and I wrote below code.
new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

Java file path f.exists() always returns false

I'm trying to create a basic Java program that allows the user create files and folders.
I want all this to happen in a folder inside my project (image attached) so I've got some doubts...
This would be my proyect tree
Is the folder "Test" correctly placed? if not how do i access to it? As you see, it's inside com.company, should I move it to src?
When I try to check if exists, it says false.
This is my code:
public class Main {
Scanner input = new Scanner(System.in);
public static void main(String[] args) {
Main main = new Main();
main.init();
}
public void init(){
File f = new File("Test"); //Here i've tried "com"+File.separator+"company"+File.separator+"Test"
System.out.println(f.exists()); //output is false here
}
}
f.getParent() says null.
But when I try: System.out.println(f.getAbsolutePath()); it shows correctly the whole path.
The point of using relative path is because i'd like this code to work on ANY computer.
Thanks in advice, hope someone could help me a bit.
If you use relative pathnames in Java, they will be resolved relative to the running application's working directory. So you need to know what the working directory is going to be.
When you are launching an application in an IDE, the working directory depends on the IDE and the launcher configs. But it is typically the file system directory that corresponds to the top of the project.
Another thing to note is that the src folder you see is special. The entries in it are typically not files and directories. The are typically Java packages and classes. So in the file system, "src" > "com.company" > "Main" is actually represented as a file with the path "src/com/company/Main.java".
This means that it is kind of wrong to put arbitrary folders and files into the "src" folder. It will work ... but it is conceptually wrong. Data files don't belong in the source tree, and certainly not data files written by your application. (And when you start using a source control system, you will find that writing data files into your source tree is going to give you a headache. I won't go into details ... but I am pretty sure that you would regret it.)
The other thing that is conceptually wrong about what you are doing is that Java programs are normally written to be free standing things. The user of your program should not need to download and install Intellij or some other IDE and load your project into it. They will want to just run it from a JAR file. In that world, the project directory and the "src" folder won't exist, and hardwiring relative paths like "src/Test" will be problematic.
So lets ignore that for now and look at what your code is currently doing
Is the folder "Test" correctly placed? if not how do i access to it? As you see, it's inside com.company, should I move it to src?
According to the image, the Test folder (actually package) >>is<< in the src Folder.
When I try to check if exists, it says false.
Your code is using the wrong path. With the "Test" folder places where you have it (according to the picture!), the relative path should be "src/Test", not "Test" or "com/company/Test".
Note that Windows accepts either "/" or "\" will work as a file separator, even though "\" is what is used conventionally.
f.getParent() says null.
That is correct. The relative path "Test" does not have a parent part. It is a simple file / directory name.
Think of it this way. Until a File with a relative path is resolved, it is not determined what directory it is relative to.
But when I try: System.out.println(f.getAbsolutePath()); it shows correctly the whole path.
Again, correct.
When you call f.getAbsolutePath() on a relative File, the runtime system prepends the path of the application's working directory, and then gives you the result.
The point of using relative path is because I'd like this code to work on ANY computer.
That relative path will NOT work on ANY computer. You are using a path that is within your project's src tree, and your project typically won't exist on an end-user's computer. (See above.)
So what should you do?
There is no single correct answer.
You could put the file / directory into the user's current / working directory.
You could put the file / directory into the user's home directory, or a hidden subdirectory in the home directory. (This is a common approach on Linux.)
You could make the pathname for the directory a command line argument
You could get the pathname from an environment variable
You could get the pathname from an application specific config file.
The best answer will depend on the context.
According to your picture the path is wrong, you should check inside the src directory:
File f = new File("src/Test");
System.out.println(f.exists());

Java: getResource image, cannot be found.

I just came up with an error in Java (using Eclipse). I want to load an image from the resource folder into the application. Using the follwoing lines:
URL url = this.getClass().getClassLoader().getResource("/resources/images/icon.png");
BufferedImage i = ImageIO.read(url);
But this results in a java.lang.IllegalArgumentException: input == null! exception.
My folder structure is:
How can I access this image? Thank you a lot!
getResource() returns null if it can't find the resource on the classpath.
In order to use getResource() you need the resources to be on the classpath. The resources directory isn't on the classpath. In Eclipse, you could add the resources folder to the classpath. Or create a new package images under srcServer and move the icon out of resources and into srcServer\images along with your source code.
Another way would be to load the image using a File rather than loading it as a classpath resource.
I believe the reason why it doesn't find the resource is due to your syntax. getClass().getClassLoader().getResource() takes the input without the leading '/' and always starts at the root of the classpath. getClassLoader().getResource() is always an absolute path, whereas getClass().getResource() is a relative path.
Just use:
URL url = this.getClass().getResource("/images/icon.png");

Java ImageIO.read(getClass().getResource()) returns null

The line
andImg = ImageIO.read(getClass().getResource("gate_and.png"));
fails with
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
I'm using Eclipse and in the navigation view under the bin folder there is the file gate_and.png, suggesting that the file is in the build path.
In the package explorer view I have
project/src/view/class - This is the class that has the code above.
and
project/images/gate_and.png
I right clicked the project folder > build path > link source to add the images folder as a source, doing this again provides a confirmation msg that says images is already in the source.
I have also tried changing gate_and.png to images/gate_and.png and /images/gate_and.png, but since the image gate_and.png is in the bin folder, I think the original is correct.
Assuming your class is in package view.random.name, then
getClass().getResource("gate_and.png")
will look for the resource in
/view/random/name/gate_and.png
relative to the root of the classpath. You apparently don't have a resource by that name there.
By setting project/images as a build path entry, Eclipse will include everything in it on the classpath. Therefore, your resource will appear at
/gate_and.png
You can access it with
getClass().getResource("/gate_and.png")
Note the leading / that means start looking at the root of the classpath, ie. it's an absolute path.
All these rules are explained in the javadoc.

Find a resource both in .jar and eclipse with the same String computation

I want to get the path to a resource for ImageIO to read out a BufferedImage from some .png s.
While developing the project I use a relative path to "/bin/stuff/icons/image.png" , but this will definetly not work when I put everything together into a .jar file, so I need a way to get the path to these resources both while testing in eclipse and when later running it within a .jar .
After a lot of trying out both finding the file and getting the input stream to the file I came to the conclusion that this approach works every time:
InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream(path)
BufferedImage image = ImageIO.read(in)
Where path is
"projectName/resourceFolder/" + nameOfResource.stuff
as found in the src directory of the eclipse project.
E.g.
"myProject/images/icon.png"
When getting only the resource and then getting the path of the resource to link to a file, you will get FileNotFoundExceptions when using a .jar (but not while testing with eclipse, so one should be warned to think that his code works).
And - no - I don't save images in the bin/ - but they are copied to this directory and thus I find them there while testing. Now everything seems to be working.
Don't put anything under the bin directory in Eclipse: if you run a clean on the project it will be erased.
What you can do is to define a new source folder like resources, and put the image there. This way it will be automatically copied to the bin folder.
If you include the resources folder into the Jar, it will be available in both environments by using something like:
ImageIO.read( getClass().getResource("/image.png") )
PS: You can evade using a different resources folder but mixing the sources and images will quickly pollute your source folder.

Categories