tags:

views:

3556

answers:

2

I'm using NetBeans, trying to change the familiar Java coffee cup icon to a png file that I have saved in a resources directory in the jar file. I've found many different web pages that claim they have a solution, but so far none of them work.

Here's what I have at the moment (leaving out the try-catch block):

URL url = new URL("com/xyz/resources/camera.png");
Toolkit kit = Toolkit.getDefaultToolkit();
Image img = kit.createImage(url);
getFrame().setIconImage(img);

The class that contains this code is in the com.xyz package, if that makes any difference. That class also extends JFrame. This code is throwing a MalformedUrlException on the first line.

Anyone have a solution that works?

+5  A: 
java.net.URL url = ClassLoader.getSystemResource("com/xyz/resources/camera.png");

May or may not require a '/' at the front of the path.

JeeBee
Thanks. This is a perfect example of why we need StackOverflow. I found 100 different "solutions" by googling before I posted this question and got an answer in 5 minutes.
Bill the Lizard
It's pretty safe to put the "/" in front. Also, it lets you take the same string and do a getResourceAsStream, which is sometimes more useful.
Daniel Spiewak
Wow--the power of StackOverflow! :-)
Onorio Catenacci
Glad to help - I'd just not one day beforehand had to do something similar :)
JeeBee
A: 

Or place the image in a location relative to a class and you don't need all that package/path info in the string itself.

com.xyz.SomeClassInThisPackage.class.getResource( "resources/camera.png" );

That way if you move the class to a different package, you dont have to find all the strings, you just move the class and its resources directory.

John Gardner