Search code examples
javaswingjframeimageiconjmenuitem

Why isn't the ImageIcon working?


I have a problem adding ImageIcon to a JMenuItem. I added it just like it was written in the tutorial but it didn't work. I have checked on Google what's wrong and didn't find. This is the code:

File.add(new JMenuItem("New", new ImageIcon("images/new.gif")));

I thought the problem might be that the icon isn't in the same folder as the .class or .java files, so I have replaced it - and still not working. The menu shows just the text.. What should I do to make i work?


Solution

  • You're passing a relative file name as argument. This file name is not relative to a class. It's relative to the JVM's current directory. And the current directory if the directory from which java is started. So if you launch the program from c:\foo, it will look for the file c:\foo\images\new.gif, even if the classes are in the jar file d:\Java\myApp.jar or in the directory e:\projects\myApp\classes.

    Files used as ImageIcon are usually bundled in the jar file of the application, along with the class files, and loaded by the class loader. If you store the file under the package com.foo.bar, you should thus use

    new ImageIcon(MyClass.class.getResource("/com/foo/bar/new.gif"));