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

标签 java swing maven icons embedded-resource

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

我有一个 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/

相关文章:

Java replaceAll 从空行中删除空格

Spring 加载 : Integration with Spring MVC maven project

Java简单正则表达式错误

java - Elasticsearch "StatusLogger Log4j2 could not find a logging implementation. Please add log4j-core to the classpath."

java - 限制 html JLabel 中的行数

java - ActionListener 阻止程序运行?

java - 最佳实践指南 : Swing

java - 如何在maven项目中构建包含jar包的war

java - "Unresolved requirement: Import-Package: javax.ws.rs"在 Tomcat 上为 Liferay 部署 OSGi 模块时

java - 引用 JPA 的问题