java - 如何从 JAR 中访问图像

标签 java resources jar

我知道以前有人问过这个问题(或类似的问题),但我还是不明白。我创建了一个具有以下内部结构的 jar:

JAR文件

-配置

---codeBehind

---命令行

---图形用户界面

---资源

在资源文件夹中,我有一张图像想用作图标,但我不知道如何获取它。我试过了

ImageIcon icon = new ImageIcon(getClass().getResource("settings.png"));
setIconImage(icon.getImage());

但是当我试图访问图标的图像时它抛出一个NullPointerException。我试图分开命令的各个部分,getResources("mypic.png") 返回 null。

关于如何获得它的任何想法?提前致谢!

最佳答案

来自 the documentation of Class :

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

所以你可能想要

getResource("/settings.png")

getResource("/resources/settings.png")

或类似的东西,取决于你的类路径,我相信。

关于java - 如何从 JAR 中访问图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2381754/

相关文章:

c# - 您将如何管理每个 c# 类的常量?

java - 将 Grizzly 的 keystore 设置为使用 jar 中的 jks

java - Struts 2如何从请求中读取参数

java - Runtime.getRuntime.exec ("who am i") 没有给出预期的结果

c++ - 如何将图像作为资源包含在 C++ 可执行文件中?

wpf - 如何从System.Windows.Media.MediaPlayer资源获取音乐?在WPF应用程序中,在线音乐播放器?

java - 在 Java 中创建命令行 Shell : Begginner help

java - org.apache.axis2.AxisFault : First Element must contain the local name, 信封,但找到了 html

java - 如何修改 JAR 中包含的文件(该文件是 IntelliJ 中的依赖项)

java - 如果我在 Spring JPA Gradle 项目的 Jar 文件中找不到 jks 文件怎么办?