简体   繁体   English

将图标添加到菜单项

[英]Add Icon to Menu Item

I want to add ImageIcon to JMenuItem to illustrate actions like New or save .我想将ImageIcon添加到JMenuItem以说明诸如Newsave 之类的操作
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):根据代码的外观,您将Image打包在 jar 文件中,您应该使用getResourceAsStream(..)getResource(..)从 jar 中提取它,如下所示(省略异常处理):

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).注意确保您的文件名及其路径的大小写正确(因为 Windows 文件系统不区分大小写,但 jar 中的文件由区分大小写的 JVM 处理)。

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 \\workspace\\YOUR_PROJECT_NAME\\IMAGES_FILE

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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