java 将图标添加到菜单项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13348349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Add Icon to Menu Item
提问by ARDA
I want to add ImageIcon
to JMenuItem
to illustrate actions like Newor save.
Why isn't the following code working for me?
我想添加ImageIcon
toJMenuItem
来说明诸如New或save 之类的操作。
为什么以下代码对我不起作用?
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 David Kroukamp
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")));
NBmake 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 处理)。
回答by tokhi
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
回答by bart-khalid
Instead of what you wrote, do that and make sure of your path image.
而不是你写的,这样做并确保你的路径图像。
newgame.setIcon(new ImageIcon(getClass().getResource("/Project1/zkre/new.gif")));
回答by ahmelq
You can just move your images file to your main project folder.
您可以将图像文件移动到主项目文件夹。
E.g:
例如:
\workspace\YOUR_PROJECT_NAME\IMAGES_FILE
\workspace\YOUR_PROJECT_NAME\IMAGES_FILE