我正在设计一个 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/