我已阅读并尝试过几十篇与此主题相关的帖子,但没有一篇正在研究中。我在每种情况下都得到空指针错误,我已经尝试将我的图像目录复制到它可能被引用的每个文件夹,甚至只是将所有图像文件转储到源文件和类文件中,没有任何工作!我已经使用getResource()方法成功加载了字体,css样式表和文本文件,但是我无法将我的图像正确地包含在可执行jar文件中。
这是代码部分,其中包含了我尝试过的一些(不是全部)备选方案。这是作为Class构造函数一部分的代码。该项目在IntelliJ。
非常感谢解决方案,谢谢!
public class Letter extends Button
{
private char value;
private Image image;
private ImageView iv;
private String imagePath;
private URL imgUrl;
private InputStream is;
private boolean clicked;
private boolean validNext;
int x, y;
/**
* CONSTRUCTOR for Letter objects
* @param value char value for key, a-z
* @param size size of image for key, in px
*/
Letter(char value, int size)
{
this.value = value;
this.imagePath = "resources/images/" + value + ".png";
//this.imagePath = "/resources/images/" + value + ".png";
//this.imagePath = "images/" + value + ".png";
this.is = getClass().
getClassLoader().
getResourceAsStream(imagePath);
this.imgUrl = this.getClass().getResource(imagePath);
this.image = new Image(this.imgUrl.toExternalForm(), size, size, true, true);
//this.image = new Image(getClass().getResourceAsStream(imagePath));
//this.image = new Image(getClass().getResourceAsStream(imgUrl.toString()));
this.iv = new ImageView(image);
this.setGraphic(iv);
this.clicked = false;
this.validNext = false;
this.x = -1;
this.y = -1;
this.setId("button");
if (this.validNext) this.setBlendMode(BlendMode.GREEN);
}
我的目录结构:
root
out
artifacts/Project/project.jar
production
Project
images
css
text
fonts
(all .class build files)
resources
images
css
text
fonts
src
(all source .java files)