【问题标题】:Add Icon to Menu Item将图标添加到菜单项
【发布时间】:2012-11-01 03:36:28
【问题描述】:

我想将ImageIcon 添加到JMenuItem 以说明新建保存等操作。
为什么以下代码对我不起作用?

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

【问题讨论】:

  • 很可能找不到图标。尝试编写一个只显示图标的小代码 sn-p,看看它是否有效。注意:通常的方法是创建一个Action 并将该Action 用于JMenuItem。然后使用可用的键值对将图标和文本放在Action 上。但这不会解决您的图标问题
  • 如果您手动操作,请查看add images to your projectanswer 以了解更多关于图像位置的说明。

标签: java swing embedded-resource


【解决方案1】:

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

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

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

【讨论】:

  • ImageIcon imageIcon = new ImageIcon(ImageIO.read(new File(getClass().getResourceAsStream("/Project1/rawaz/new.gif"))));
  • @ARDA 查看更新,不知道为什么我添加了new File() 东西一定是疲劳了:P
【解决方案2】:

也许请确保您获得正确的图像路径:

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

【讨论】:

    【解决方案3】:

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

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

    【讨论】:

      【解决方案4】:

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

      例如:

      \workspace\YOUR_PROJECT_NAME\IMAGES_FILE

      【讨论】:

        猜你喜欢
        • 2019-08-26
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-09
        • 1970-01-01
        • 2019-07-09
        • 2022-11-11
        • 1970-01-01
        相关资源
        最近更新 更多