将图像图标添加到 buttons/labels Swing

Add image icons to buttons/labels Swing

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

我有一个 Maven 项目,我想在按钮上使用图像。我把图像放在 src/main/res folder 中。在 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,但没有任何效果。

    URL url = getClass().getResource(".");
    System.out.println(url);
    url = getClass().getResource("cross_icon.jpg");
    System.out.println(url);
    Image img = ImageIO.read(url);
    System.out.println(img);
    button.setIcon(new ImageIcon(img));

getResource () 将创建 url,方法是在给定路径后附加基本路径(您的 .class 的路径)

通过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').

PS

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

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