Add image icons to buttons/labels Swing

拟墨画扇 提交于 2019-12-10 20:25:55

问题


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.


回答1:


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



回答2:


    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 () will create url, by appending the given path with the base path(the path of your .class)



来源:https://stackoverflow.com/questions/44844205/add-image-icons-to-buttons-labels-swing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!