我有这个方法:
private ArrayList<Image> imageArray(File files[]) {
ArrayList<Image> images = null;
for(int x = 0; files.length > x; x++) {
//I want to add each PNG-File to the Image-Array
try {
images.add(x, ImageIO.read(files[x])); //Demo.imageArray(Demo.java:23)
}catch(IOException | ArrayIndexOutOfBoundsException exception) {
exception.printStackTrace();
}
//Now I scale each Image, so it fits the screenSize
int newWidth = (int) screenSize.getWidth(),
newHeight = newWidth * images.get(x).getHeight(null) / images.get(x).getWidth(null);
if(newHeight > screenSize.getHeight()) {
newHeight = (int) screenSize.getHeight();
newWidth = newHeight * images.get(x).getWidth(null) / images.get(x).getHeight(null);
}
images.set(x, images.get(x).getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH));
}
return images;
}
导致此异常:
Exception in thread "main" java.lang.NullPointerException
at Demo.imageArray(Demo.java:23) //I've marked the position in the code!
at Demo.main(Demo.java:47) // Just, when I want to use the method anywhere
为什么我会收到错误,我该如何解决?当我想使用方法时,我添加了一个参数,如下所示:
imageArray(new File[] {new File("filePath to PNG-Image"),
new File("filePath to PNG-Image")})
答案 0 :(得分:1)
一个简单的解决方案是初始化images
。
所以不要只是这样做:
ArrayList<Image> images = null;
这样做:
ArrayList<Image> images = new ArrayList<>();