Java Swing : ImageIcon not appearing in eclipse?

标签 java eclipse swing

我正在设计一个 GUI。我创建了一个菜单栏并将菜单项添加到菜单并已设置菜单栏。 我的问题是我无法向 Menuitem 添加图标(图标未出现在 Eclipse 中)。

我就是这样做的: 我的 .png 文件位于 D:/something/src/resources/new.png

JMenuBar menuBar = new JMenuBar();
JMenu File = new JMenu("File");
menuBar.add(File);
java.net.URL imageURL = this.getClass().getResource("/resources/new.png");
System.out.println(imageURL); //imageURL is printing correctly in console
ImageIcon im = new ImageIcon(imageURL);
JMenuItem newItem = new JMenuItem("New", im);

File.add(newItem);
setJMenuBar(menuBar);

我也面临着向工具栏中的按钮添加图标的类似问题。猜猜,也是同样的原因。谁能告诉我我做错了什么。

注意:我也尝试过使用 .jpg、.jpeg 和 .ico 文件。但 eclipse 中什么也没有出现!我正在使用 Windows 和 MS Access 数据库。

最佳答案

资源中的文件通常最终位于 Jar 的根目录中。尝试:

java.net.URL imageURL = this.getClass().getResource("/new.png");

如果您失败,请展开 Jar 并检查图像是否位于您认为的位置。

关于Java Swing : ImageIcon not appearing in eclipse?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8991523/

相关文章:

java - 增加 Gridlayout 中的行大小

java - 一段Swing代码如何变成真正的图形应用程序

java - 如果 test/clean install/package 命令带有 args(-D) 或配置文件标记 (-P),Maven 容器不会运行

java - struts 2中如何设置 Action 范围

java - 在 url 中插入双引号时,索引处的查询中存在非法字符

eclipse - 运行所有测试

java - 将 Maven 项目部署到 Tomcat 7,仍然得到 404

java - 通过从 Jframe 类 3 中的 jtable 中选择项目来更改 JFrame class1、JFrame class2...中的文本字段的值

java - 共享/类和war文件下的Java类-在tomcat中加载的优先级

安卓/Eclipse : how can I add an image in the res/drawable folder?