简体   繁体   中英

Add Icon to Menu Item

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"));

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).

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

而不是你写的,这样做并确保你的路径图像。

newgame.setIcon(new ImageIcon(getClass().getResource("/Project1/zkre/new.gif")));

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

Eg:

\\workspace\\YOUR_PROJECT_NAME\\IMAGES_FILE

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM