I want to set icon to my JFrame. I do the following:
Image icon = Toolkit.getDefaultToolkit().getImage(\"src/images/icon.jpg\");
this.setIconImage(icon);
This should do it assuming you can import javax.imageio.ImageIO:
Image icon = ImageIO.read(this.getClass().getResource("/src/images/icon.jpg"));
this.setIconImage(icon);
Looking at the source code of URLImageSource, it appears that the reason that getConnection
throws an NPE is that it has a null
for the url. And that leads me to suspect that
getClass().getResource("/src/images/icon.jpg")
is returning null
. It would do that if it could not locate a resource with that pathname.
I bet that the problem is that you've got the path wrong.
To prove / disprove this, you should run jar tvf
on the JAR file, and look for the line that matches "icon.jpg"
. Is the corresponding pathname the same as what you are using? If not, use the pathname from the matching line in the getResource
call and it should work. Alternatively, if the file doesn't show up at all, look at the NetBeans build configs that tell it what to put in the JAR file. (I'm not a NetBeans user, so I can't say where you would need to look ...)
If that leads you absolutely nowhere, another possibility is that getClass().getResource(...)
is using a classloader that doesn't know about the JAR file containing the image. (This seems pretty improbable to me ...)
.."/src/images/icon.jpg"..
The '/src' prefix of the address seems suspicious. Many apps. will provide separate 'src' and 'build' directories, but it normally ends up that the 'src' prefix is not used in the resulting Jar. I recommend trying..
.."/images/icon.jpg"..
& also triple checking that the image is in the location of the Jar that the code is expecting to find it.
You can simply create a package inside the main source, and incluse your images in this package. Then, just call the images in your main class like:
ImageIcon a = new ImageIcon(MainClass.class.getResource("/Package/Image.jpg"));
JFrame f = new JFrame("Edit Configure File");
//Image image = ImageIO.read(getClass().getResource("images/ctx.Icon"));
f.setIconImage(new ImageIcon("images/ctx.PNG").getImage());//this works for me finally
//f.setIconImage(image);
//f.setIconImage(Toolkit.getDefaultToolkit().getImage(getClass().getResource("images/ctx.PNG")));
getResource()
loads a resource from classpath, not an OS path, and the after compilation your classpath will not include the /src
folder, but rather just its contents. So you'd better try /images/icon.jpg
.
Also you may find this discussion somewhat useful.