gpt4 book ai didi

java - 将图像图标添加到按钮/标签 Swing

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:34:54 25 4
gpt4 key购买 nike

我知道这个问题已经发布了,但我已经尝试了我发现的所有方法,但没有任何效果。

我有一个 Maven 项目,我想在按钮上使用图像。我将图像放在 src/main/res 文件夹中。在 Maven clean/Maven 安装之后,我所有的图像都在 target/classes 文件夹中。我希望图像位于 .jar 文件中,这样我在使用它时就不需要创建单独的文件夹。

这是我尝试用来为我的按钮上的新图标加载图像的代码:

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);

但我得到一个input == null。我尝试使用 main/res/cross_icon.jpgres/cross_icon.jpg,但没有任何效果。

最佳答案

通过Class.getResource加载资源时,如果是绝对路径,必须在资源路径的开头加上/

Image img = ImageIO.read(getClass().getResource("/cross_icon.jpg"));

参见 Class.getResource 的 javadoc

Before delegation, an absolute resource name is constructed from the given resource name using this algorithm:

  • 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

    Where the modified_package_name is the package name of this object with '/' >substituted for '.' ('\u002e').

附言

如果您使用 ClassLoader.getResource,资源名称总是被解释为绝对路径。例如

Image img = ImageIO.read(getClass()
.getClassLoader()
.getResource("cross_icon.jpg"));

关于java - 将图像图标添加到按钮/标签 Swing,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44844205/

25 4 0