我的程序使用Image.class,它可以帮助我接收图像。
Image img = new ImageIcon("Shooter2D/res/background.jpg").getImage();
当程序从开发环境运行时 - 一切正常,编译 jar 文件后 - 不起作用。 告诉我如何正确设置在 IDE (Intellij IDEA) 和存档中工作的路径。 Shooter2D.jar 包含:
- META-INF
Manifest-Version: 1.0
Main-Class: Shooter2Dv22082013.Main
- res
all pictures
- Shooter2Dv22082013
all .class files, main is Main.class
最佳答案
这就是 the javadoc关于ImageIcon的构造函数的说明:
Creates an ImageIcon from the specified file. The image will be preloaded by using MediaTracker to monitor the loading state of the image. The specified String can be a file name or a file path.
(强调我的)
您的图像未存储在文件中。它不在您的文件系统中。它位于类路径中的一个 jar 中。这就是您想要加载它的地方。无论应用程序的 jar 文件位于最终用户计算机上的何处,您的程序都希望从该 jar 文件加载它。并且此 jar 文件中的所有资源都可以从 ClassLoader 中获取。
所以你应该使用
new ImageIcon(MyClass.class.getResource("/res/background.jpg"))
或
new ImageIcon(MyClass.class.getClassLoader().getResource("res/background.jpg"))
关于java - java中的绝对/相对路径(jar、ide),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18379674/