【发布时间】:2020-12-20 07:11:19
【问题描述】:
我有一个带有 Swing GUI 的应用程序,我想在菜单栏中添加一个带有搜索按钮(lupe 图标)的搜索字段。但是,不会显示 lupe 图标。这是我的代码:
public class Ui_Frame {
public static void main(String[] args) {
SwingUtilities.invokeLater(Ui_Frame::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Myframe");
...
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon("Resources/lupe_icon.png");
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
...
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setVisible(true);
我的项目结构是这样的
Project
Src
Ui_Frame.java
Resources
lupe_icon.png
生成的按钮根本不显示任何图标:
我没有收到任何错误消息,它编译没有问题。即使我尝试从 new ImageIcon(...) 捕获任何异常,我也没有得到任何关于错误是什么的提示。
关于我在这里做错了什么有什么想法吗?
编辑:
这是一个最小的例子:
import javax.swing.*;
public class test {
private static JFrame f;
public static void main(String[] args) {
SwingUtilities.invokeLater(test::createAndShowGUI);
}
private static void createAndShowGUI() {
f = new JFrame("Test");
JMenuBar menubar = new JMenuBar();
Icon lupeIcon = new ImageIcon(test.class.getResource("/Resources/lupe_icon.png"));
JButton j_searchButton = new JButton(lupeIcon);
menubar.add(j_searchButton);
f.setJMenuBar(menubar);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.pack();
f.setSize(500,500);
f.setVisible(true);
}
}
如您所见,我现在按照@AndrewThompson 和@SergiyMedvynskyy 的建议使用class.getResource(...) 加载图像,但这并不能解决问题。另外有人告诉我,我的类不应该是静态的,但是因为我的 Main 需要是静态的才能运行程序,并且有人告诉我应该使用 SwingUtilities.invokeLater(test::createAndShowGUI); 启动 UI
这也强制 createAndShowGUI() 是静态的,我不知道如何使它不是静态的。
【问题讨论】:
-
看起来可能是加载资源的问题。你能检查
lupeIcon是否为空吗? -
@maloomeister 我查过了,它不为空。
-
也许你应该通过
new ImageIcon(Ui_Frame.class.getResource("Resources/lupe_icon.png"));加载你的图标 -
@SergiyMedvynskyy 好的,我试过了,没有解决问题:(。我可能需要以任何特殊方式格式化我的 lupe_icon.png 吗?目前它只是我下载的一些 png
-
1) 应用程序资源在部署时将成为嵌入式资源,因此明智的做法是立即开始访问它们。 embedded-resource 必须通过 URL 而不是文件访问。请参阅info. page for embedded resource 了解如何形成 URL。 2) 为了尽快获得更好的帮助,edit 添加minimal reproducible example 或Short, Self Contained, Correct Example。 3) 例如,获取图像的一种方法是热链接到this Q&A 中看到的图像。 ..
标签: java swing icons embedded-resource