繁体   English   中英

将图标添加到菜单项

[英]Add Icon to Menu Item

我想将ImageIcon添加到JMenuItem以说明诸如Newsave 之类的操作
为什么以下代码对我不起作用?

   JMenu file = new JMenu("File");
   menubar.add(file);
   JMenuItem newgame = new JMenuItem("New");
   file.add(newgame);
   newgame.setIcon(new ImageIcon("/Project1/zkre/new.gif"));

根据代码的外观,您将Image打包在 jar 文件中,您应该使用getResourceAsStream(..)getResource(..)从 jar 中提取它,如下所示(省略异常处理):

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

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

也许确定您是否获得了正确的图像路径:

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

您可以将图像文件移动到主项目文件夹。

例如:

\\workspace\\YOUR_PROJECT_NAME\\IMAGES_FILE

暂无
暂无

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

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