Java:如何将图标放入jar(或exe)中?通往它的路径是什么



我想做的是在程序运行时更改程序的图标。

我找到的代码是:

      try {
          String imagePath = "res/Image.png";
          InputStream imgStream = this.getClass().getResourceAsStream(imagePath );
          BufferedImage myImg;
          myImg = ImageIO.read(imgStream);
          this.setIconImage(myImg);
      } catch (IOException e) {
          e.printStackTrace();
      }

我的问题是:我把我的图像放在哪里,我如何获得它的路径?最终结果是有一个我只需要转移的.exe(或最坏的情况是.jar),所以我想在 exe 中拥有图标。

Class.getResource(String name) expects a resource name relative to the location the class is loaded from. So if your resource is called image.jpg, then image.jpg must be in the same folder where the class is whose getResource() method you're calling.

如果以/字符开头,您还可以在 jar 内指定一个绝对文件夹:

getClass().getResource("/resources/images/image.jpg");

在这种情况下,图像.jpg必须位于 jar 内的/resources/images 文件夹中或源文件夹中(将由 IDE 复制到 bin 文件夹中)。

最新更新