Search code examples
javaswingmaveniconsembedded-resource

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.

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

but I get a input == null. I tried using main/res/cross_icon.jpg or res/cross_icon.jpg, but nothing worked.


Solution

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

    See the javadoc of Class.getResource

    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

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