3

I want to add ImageIcon to JMenuItem to illustrate actions like New or save.
Why isn't the following code working for me?

   JMenu file = new JMenu("File");
   menubar.add(file);
   JMenuItem newgame = new JMenuItem("New");
   file.add(newgame);
   newgame.setIcon(new ImageIcon("/Project1/zkre/new.gif"));
Tomáš Zato
  • 50,171
  • 52
  • 268
  • 778
ARDA
  • 31
  • 1
  • 1
  • 2
  • 1
    Most likely the icon can not be found. Try writing a small code snippet which just shows the icon, and see whether that works. Note: The normal way is to create an `Action` and use that `Action` for the `JMenuItem`. You then place the icon and text on the `Action` using the available key-value pairs. But this will not solve your icon issue – Robin Nov 12 '12 at 17:31
  • 1
    Please have a look at how to [add images to your project](http://stackoverflow.com/a/9866659/1057230) and this [answer](http://stackoverflow.com/a/11372350/1057230) for more clarification about the placement of your images, if you doing things manually. – nIcE cOw Nov 12 '12 at 17:34

5 Answers5

5

By the looks of your code you have your Image packaged in your jar file, you should use getResourceAsStream(..) or getResource(..) to extract it from the jar like so (Exception Handling omitted):

ImageIcon imageIcon=new ImageIcon(ImageIO.read(getClass().getResourceAsStream("/Project1/rawaz/new.gif")));

NB make sure the case of your file name and its path are correct (as Windows file system is not case sensitive but files inside the jar are handled by JVM which is case sensitive).

David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
  • ImageIcon imageIcon = new ImageIcon(ImageIO.read(new File(getClass().getResourceAsStream("/Project1/rawaz/new.gif")))); – ARDA Nov 13 '12 at 10:02
  • @ARDA see update, dont know why i added the `new File()` thing must have been fatigue :P – David Kroukamp Nov 13 '12 at 10:05
4

Maybe make sure if you are getting the right image path:

java.net.URL imageURL = this.getClass().getResource("YOUR_IMAGE_PATH");
System.out.println(imageURL); //imageURL is printing correctly in console
ImageIcon image = new ImageIcon(imageURL);
// now add the image to your menubar
David Kroukamp
  • 36,155
  • 13
  • 81
  • 138
tokhi
  • 21,044
  • 23
  • 95
  • 105
0

Instead of what you wrote, do that and make sure of your path image.

newgame.setIcon(new ImageIcon(getClass().getResource("/Project1/zkre/new.gif")));
bart-khalid
  • 198
  • 1
  • 9
0

I checked this works!!

Path example => "src/assets/file.png"

ImageIcon icon = new ImageIcon("Here must be your path");  
JMenuItem left = new JMenuItem("ItemText",icon);
Arto
  • 71
  • 3
-1

You can just move your images file to your main project folder.

E.g:

\workspace\YOUR_PROJECT_NAME\IMAGES_FILE

Rahul Sharma
  • 5,614
  • 10
  • 57
  • 91
ahmelq
  • 593
  • 7
  • 11