I'm trying to make a java program and have an application icon that is resources/Icon.png. My code at the moment is
ClassLoader cldr = this.getClass().getClassLoader();
URL url = cldr.getResource( "//resources//Icon.png" );
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
this.setIconImage( img );
However I'm getting
Uncaught error fetching image: java.lang.NullPointerException
Am I referencing the location of the icon correctly? resources is a package in the program.
When using the ClassLoader to load a resource, the path must be a slash-separed path, not starting with a slash:
resources/Icon.png
If using the class directly (SomeClass.class.getResource(...)), then it can start with a slash to look for the resource by starting at the root of the classpath, or it can not start with a slash to look for the resource by starting at the same package as the class.
Not sure if this will fix it, but change your code so you're using a File and BufferedImage. Let me know if it doesn't.
Edit: Didn't see the bottom. Instead of URL, use a File.
Related
I have a jruby Swing application in a jar. In my source code main.rb I have an image specified as
img = ImageIcon.new("img/test.png")
which does not load. My path looks like this
lib/main.rb
lib/img/test.png
Is there a way to specify the relative path to the image?
In addition, I've found the equivalent way of doing this in Java using getResource
new javax.swing.ImageIcon(getClass().getResource("myimage.jpeg"))
How would I implement this in jruby?
Just like in Java - your file is not a file, it has to be addressed as a resource-inna-jar:
java.net.URL url = getClass().getResource("img/test.png");
ImageIcon image = new ImageIcon(url);
Didn't try, but translated into Ruby, I believe it's something like
url = JRuby.runtime.jruby_class_loader.get_resource("/lib/img/test.png")
image = ImageIcon.new(url)
Why is following code throwing this exception?
java.lang.IllegalArgumentException: Invalid URL or resource not found
Here is the code:
File ff=new File("images/a.jpg");
if (ff.exists()) {Image ii=new Image(ff.getPath());}
From the Javadocs:
All URLs supported by URL can be passed to the constructor. If the
passed string is not a valid URL, but a path instead, the Image is
searched on the classpath in that case.
The path you get is a relative path, but not (necessarily) relative to the classpath, which is how the Image constructor is interpreting it.
Try
Image ii=new Image(ff.toURI().toURL().toExternalForm());
or, depending on how you have your project structure set up
Image ii=new Image(getClass().getResource("images/a.jpg").toExternalForm());
The second version will work if the image file is packaged along with the application in a jar file.
I want to load an image which is in my projet folder as : /src/images/URL.jpg
I tried this code :
BufferedImage image = ImageIO.read(getClass().getResource("/images/URL.jpg"));
But I'm getting this error :
Exception in thread "AWT-EventQueue-0" java.lang.IllegalArgumentException: input == null!
at javax.imageio.ImageIO.read(ImageIO.java:1388)
at Personel.PersonnelMainForm.print(PersonnelMainForm.java:464)
How can I solve this problem ?
From personal experience I use:
BufferedImage image = ImageIO.read(getClass().getResourceAsStream("/images/image.jpg"));
I get the resource as a stream and that seems to work fine for me.
You can try this version of read, which takes File as an argument.
BufferedImage image = ImageIO.read(new File("path"));
where path is the path to you file, absolute or relative as you need.
Another option, if you really want to load it as a resource, would be editing your classpath, as per this question.
I suppose you have a java class in the package.
You have to move up so many times as package levels.
Example:
Java class is defined as org.test.MyClass
you have to go up twice (../../) to be in the main directory.
I've made an audio player and the jar was made with netbeans. To load the images I've used:
ClassLoader cl = this.getClass().getClassLoader();
URL playerIconURL = cl.getResource("tp/audioplayer/Images/icon.png");
if (playerIconURL != null){
ImageIcon playerIcon = new ImageIcon(playerIconURL);
frame.setIconImage(playerIcon.getImage());
}
else{
System.err.println("cannot load player icon");
}
I mention that the folder Images is in the src/tp/audioplayer.
When I'm running the application inside netbeans everything is allright, but when I execute the jar in command prompt,the application starts but it's blank and it blocks and I get:
Can you tell me what I've done wrong or what is the problem? Thanks in advance!
If tp is in your classpath you will have to load it with cl.getResource("/tp/audioplayer/Images/icon.png") if tp is NOT a source folder (but still added to the buildpath.
If you add tp as a sourcefolder then
cl.getResource("/audioplayer/Images/icon.png")
Note that jars are casesensitive, make sure you the case-sensitive file-path.
Try any of these:
// using getResourceAsStream
InputStream is = this.getClass().getResourceAsStream( "picture.gif" );
// or
InputStream is = MyClass.class.getResourceAsStream( "stuff.ser" );
// or
InputStream is = MyApp.class.getClassLoader().getResourceAsStream( "InWords.properties" );
The resource in the jar file must be qualified with same package name as the class you call getResourceAsStream from. Alternatively, you can use an absolute name beginning with a / where dots get mapped to /s. If you don’t have a lead /, you have a relative name, and the name of the package will be prepended. If you use a /, you must include the name of the package yourself, or whatever name the resource is filed under in the jar.
For example you could specify /com/mindprod/mypackage/mystuff.ser or /com.mindprod.mypackage.mystuff.ser or simply mystuff.ser. Don’t use Windows style filenames with . These are not filenames, but Java resources that live along with the class files either in jars or sometimes freestanding on disk, or on the server.
In theory, getResourceAsStream will look in the local classpath, in the jar and in the directory where the class file was loaded from.
I have a Java project called MyProject. I have a few different packages (keeping names simple for the purpose of this question), as follows:
src/PackageA
src/PackageA/PackageAa
src/PackageA/PackageAa/PackageAaa
src/PackageB
src/PackageB/PackageBa
src/PackageB/PackageBa/PackageBaa
I have a class
src/PackageA/PackageAa/PackageAaa/MyJavaFile.java
And I have an image
src/PackageB/PackageBa/PackageBaa/MyImage.png
Inside of MyJavaFile.java, I would like to declare an Image oject of MyImage.png
Image img = new Image(....what goes here?...)
How can I do this?
You could either call Class.getResource and specify a path starting with /, or ClassLoader.getResource and not bother with the /:
URL resource = MyJavaFile.class
.getResource("/PackageB/PackageBa/PackageBaa/MyImage.png");
or:
URL resource = MyJavaFile.class.getClassLoader()
.getResource("PackageB/PackageBa/PackageBaa/MyImage.png");
Basically Class.getResource will allow you to specify a resource relative to the class, but I don't think it allows you to use ".." etc for directory navigation.
Of course, if you know of a class in the right package, you can just use:
URL resource = SomeClassInPackageBaa.class.getResource("MyImage.png");
(I'm assuming you can pass a URL to the Image constructor in question. There's also getResourceAsStream on both Class and ClassLoader.)
you can use relative path since the the relative path is project folder.
ImageIcon img = new ImageIcon("src/PackageB/PackageBa/PackageBaa/MyImage.png");
/folderB/folderBa/folderBaa/MyImage.png
The image can stored into a project folder location .eg: /images/MyImage.png
Then try:
Image img = new Image(/images/MyImage.png);
Using a file path is not possible when running a program that's in a jar file, especially if the program is being loaded as an applet or WebStart application then you can use ClassLoader to get image.
use the following code to load the images:
ClassLoader cldr = this.getClass().getClassLoader();
java.net.URL imageURL = cldr.getResource("/PackageB/PackageBa/PackageBaa/MyImage.png");
ImageIcon aceOfDiamonds = new ImageIcon(imageURL);
This IS the best way to handle all images and icons in a JAR App.
Once you've zipped up all of your images and icons into its own JAR file - Configure your build path by adding the images JAR file into your libraries tab so that its now included in your classpath.
Then simply use the following 3x lines of code at the start of your constuctor to access any image you need for anything including a SystemTray image which doesn't accept the simple ImageIcon's as its main icon (weird I know). The 3x lines are:
URL iconUrl = this.getClass().getResource("/image-iconb.png");
Toolkit tk = this.getToolkit();
imageIcon = tk.getImage(iconUrl);
(imageIcon is just a constructor declared Image variable)
Now you can set a window icon as simply as:
setIconImage(imageIcon );
and at the same time use the same variable when setting the System TrayIcon by declaring:
trayIcon = new TrayIcon(imageIcon, "SystemTray Demo", popupMenu);
The above allows you to declare Images or ImageIcons easily and centrally without running the risk of not keeping image resources in the right place. It keeps it nice and tidy, with the JAR containing all your images automatically compiled at run time and distribution of your program.
As a bonus, once the JAR is registered in your classpath - you can keep adding any other images into the same JAR at any time without any fuss too - Everything just works and the added images are instantly available to your app.
Much better in my view.
Use the getResource method to read resources inside the src root. For example, the following code retrieves images from a folder src/images.
// Get current classloader
ClassLoader cl = this.getClass().getClassLoader();
// Create icons
Icon saveIcon = new ImageIcon(cl.getResource("images/save.gif"));
Icon cutIcon = new ImageIcon(cl.getResource("images/cut.gif"));
The example assumes that the following entries exist in the application's JAR file:
images/save.gif
images/cut.gif
Image img = new Image("./src/PackageB/PackageBa/PackageBaa/MyImage.png");
This shall go the path of the image is first inside src (source) then package so the program would access the image this way.