如何将 PNG 文件数组添加到 ArrayList<Image> - Java



我有这个方法:

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")})
一个简单的

解决方案是初始化images

因此,与其只是这样做:

ArrayList<Image> images = null;

这样做:

ArrayList<Image> images = new ArrayList<>();

相关内容

最新更新