将图标图标添加到按钮/标签Swing [英] Add image icons to buttons/labels Swing
问题描述
我知道这个问题已经发布了,但是我已经尝试了所有我找到的并且没有任何效果。
I know that this question has already been posted, but I've tried everything I found and nothing worked.
我有一个Maven项目,我想要使用按钮上的图像。我将图像放在 src / main / res文件夹
中。在Maven clean / Maven安装后,我的所有图像都可以在 target / classes
文件夹中找到。我希望图像位于 .jar
文件中,这样我在使用它时就不需要创建单独的文件夹了。
I have a Maven project, and I want to use images on buttons. I put the images in the src/main/res folder
. After a Maven clean/ Maven install, all my images are found in the target/classes
folder. I want the images to be inside the .jar
file, so that I don't need to create a separate folder when using it.
这是我尝试用来加载按钮上的新图标图像的代码:
This is the code I try to use to load the image for a new icon on my button:
JButton button = new JButton();
try {
Image img = ImageIO.read(getClass().getResource("cross_icon.jpg"));
button.setIcon(new ImageIcon(img));
} catch (Exception ex) {
System.out.println(ex);
}
subsPanel.add(button);
但我得到输入== null
。我尝试使用 main / res / cross_icon.jpg
或 res / cross_icon.jpg
,但没有任何效果。
but I get a input == null
. I tried using main/res/cross_icon.jpg
or res/cross_icon.jpg
, but nothing worked.
推荐答案
如果是,则必须在资源路径的开头放置 /
通过 Class.getResource
加载资源时的绝对路径。
You must put a /
at the beginning of the resource path if it is an absolute path when loading a resource via Class.getResource
.
Image img = ImageIO.read(getClass().getResource("/cross_icon.jpg"));
在委托之前,使用此算法从给定资源名称构造绝对资源名称:
Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:
- 如果名称以'/'('\ u002f')开头,则>资源的绝对名称是'/'后面的名称部分。
-
否则,绝对名称的格式如下:
- If the name begins with a '/' ('\u002f'), then the absolute name of the >resource is the portion of the name following the '/'.
Otherwise, the absolute name is of the following form:
modified_package_name/name
其中modified_package_name是此对象的包名称,其中'/'>替换为'。' ('\ u002e')。
Where the modified_package_name is the package name of this object with '/' >substituted for '.' ('\u002e').
PS
如果您使用 ClassLoader.getResource
,则资源名称为总是被解释为绝对路径。例如
If you use ClassLoader.getResource
the resource name is always interpreted as an absolute path. E.g.
Image img = ImageIO.read(getClass()
.getClassLoader()
.getResource("cross_icon.jpg"));
这篇关于将图标图标添加到按钮/标签Swing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!