如何确保我的 .jar 包中包含了图片?

huangapple go评论86阅读模式
英文:

How can I ensure that images are included in my .jar package?

问题

我刚刚完成了我的第一个带有GUI的Java程序,并在NetBeans中设置了所有选项,以便项目创建一个.jar文件,目前该文件显示我的窗体并连接到数据库。
我遇到的问题是,当我运行程序时(我必须从终端运行它,因为点击.jar文件可能是问题的一部分?),我的所有图像都不加载。
我尝试过以下方法:

1)进入项目库首选项,并添加位于我的P3Game文件夹(项目的根目录)内的/img文件夹,但没有成功。
2)尝试直接复制图像到生成的/dist文件夹,但然后无法通过库首选项添加图像,因为它不是文件夹或库。
3)在编译后手动复制img文件夹到dist(编译后),并将文件路径设置为dist/img/imgName.png,这样可以工作,但是,每次构建/编译项目时,dist文件夹中的img文件夹都会被完全清除(只保留内容)

任何帮助都将不胜感激。

编辑1:这是我将图像添加到程序的方式,这在NetBeans中有效,但在其他地方运行程序时无效。

public void setGrassIcon() throws IOException {
    this.grassIcon = new ImageIcon(ImageIO.read(new File("img/Grass.png")));
}
英文:

I have just finished my first proper java program with a GUI, and have set all of the options in netbeans in order for the project to create a .jar file which is currently displaying my Frame and connecting to the database.
The issue I am having is that when I run the program (I have to run it from terminal as clicking the .jar might be part of the issue?), none of my images load.
I have tried the following;

  1. Going into project Library preferences, and adding the /img folder which resides within my P3Game folder (root dir of the project) with no avail.
  2. Tried directly copying the images to the generated /dist folder but then I cant add the images via the library pref's due to it not being a folder or library.
  3. Manually copying over the img folder into dist (after compiling) and setting the file path to dist/img/imgName.png and it worked, however, any time I build/ compile the project, the img folder within dist gets completely wipes (just the contents)

ANY help would be much appreciated.

EDIT1: this is how im adding the images into the program, and this works from netbeans, but not from running the program elsewhere.

public void setGrassIcon() throws IOException {
        this.grassIcon = new ImageIcon(ImageIO.read(new File("img/Grass.png")));
}

</details>


# 答案1
**得分**: 1

如果您从命令行运行,图片必须在您的类路径中:

    java -cp "pictures\*"  

加载图片的代码是什么样的?
可能是这样的:

    Example.class.getResource("pictures/mypic.png");

<details>
<summary>英文:</summary>

If you run from command line, the pictures have to be in your classpath:

    java -cp &quot;pictures\*&quot;  

How does the code looks like to load the images?
Could look like this:

    Example.class.getResource(&quot;pictures/mypic.png&quot;);



</details>



huangapple
  • 本文由 发表于 2020年10月19日 16:09:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/64423444.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定