Anna Marie
Anna Marie

Reputation: 1

Java Swing: ImageIcon not appearing in eclipse?

I am designing a GUI. I have created a Menubar and added Menu items to Menu and Have setMenubar. My problem is i am not able to add an icon (icon is not appearing in eclipse) to the Menuitem.

This is how I did: I have my .png file in D:/something/src/resources/new.png

JMenuBar menuBar = new JMenuBar();
JMenu File = new JMenu("File");
menuBar.add(File);
java.net.URL imageURL = this.getClass().getResource("/resources/new.png");
System.out.println(imageURL); //imageURL is printing correctly in console
ImageIcon im = new ImageIcon(imageURL);
JMenuItem newItem = new JMenuItem("New", im);

File.add(newItem);
setJMenuBar(menuBar);

I am facing the similar problem adding icon to a button in Toolbar too. Guess, it is same cause. Could anyone please tell me what I am doing wrong.

Note: I have tried with .jpg, .jpeg and .ico files too. But nothing is appearing in eclipse!. I am using Windows & MS Access database.

Upvotes: 0

Views: 3016

Answers (2)

nIcE cOw
nIcE cOw

Reputation: 24626

Hopefully the resources folder, is the Source Folder that you had created by right clicking your Project. So you can use this also to retrieve images.

URL url = ClassLoader.getSystemResource(path);

where path = "new.png"

Or as quoted by you :

"This is how I did: I have my .png file in D:/something/src/resources/new.png" Try to change the location of the resources folder inside classes/bin folder instead of src. So it must look like this D:/something/classes/resources/new.png Now if you will use

URL url = ClassLoader.getSystemResource(path);

then path = "resources/new.png";

Then i guess your way of doing will run too.

Hopefully this might help you in some way.

Regards.

Upvotes: 0

Andrew Thompson
Andrew Thompson

Reputation: 168845

A file in resources would typically end up at the root of a Jar. Try:

java.net.URL imageURL = this.getClass().getResource("/new.png");

If that fails for you, expand the Jar and check the image is located where you think it is.

Upvotes: 1

Related Questions