我有一个具有BufferedImage的ArrayList的类,但是我遇到了一个严重的问题。有两种可能性:
- ArrayList都是静态的,因此它们的获取方法是:这很好,因为应用程序正在启动并且动画运行完美。但是因为有静电,所以我不能拥有不同的动画。
- ArrayList(和它们的getter)不是静态的:当调用getDown()时,我得到一个NullPointerException,它指向调用它的精确时刻。
在此之前,我使用了简单的数组,我相信使用ArrayLists可以解决问题,但没有区别。
我不明白为什么会这样做,你能帮我解决这个问题吗?
public class AnimUnit {
private static final int width = 32, height = 32, nbframe = 4;
private ArrayList<BufferedImage> down;
private ArrayList<BufferedImage> up;
private ArrayList<BufferedImage> right;
private ArrayList<BufferedImage> left;
private ArrayList<BufferedImage> idle;
public AnimUnit(SpriteSheet sheet) {
this.down = new ArrayList<BufferedImage>();
this.up = new ArrayList<BufferedImage>();
this.left = new ArrayList<BufferedImage>();
this.right = new ArrayList<BufferedImage>();
this.idle = new ArrayList<BufferedImage>();
for(int i = 0; i < nbframe; i++)
down.add(sheet.crop((width*2)+2, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
up.add(sheet.crop((width*3)+3, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
left.add(sheet.crop((width)+1, (height*i)+i, width, height));
for(int i = 0; i < nbframe; i++)
right.add(sheet.crop((width*4)+4, (height*i)+i, width, height));
for(int i = 1; i < nbframe; i++)
idle.add(sheet.crop(0, (height*i)+i, width, height));
}
public static int getWidth() {
return width;
}
public static int getHeight() {
return height;
}
public ArrayList<BufferedImage> getDown() {
return down;
}
public ArrayList<BufferedImage> getUp() {
return up;
}
public ArrayList<BufferedImage> getRight() {
return right;
}
public ArrayList<BufferedImage> getLeft() {
return left;
}
public ArrayList<BufferedImage> getIdle() {
return idle;
}
答案 0 :(得分:1)
目前,您班级中维护的属性都是静态的。您正在使用构造函数为它们赋值,这可能会误导您的类的用户,因为您的类没有非静态属性。如果你的构造函数没有被调用,那么它们就不会被初始化(并且在访问时会抛出空指针异常),但是除静态方法之外的构造对象都是无用的。
从您的所有属性和方法中删除“静态”一词,我认为它会像您想要的那样工作。
AnimUnit animUnitA=new animUnit(spriteSheetA);
AnimUnit animUnitB=new animUnit(spriteSheetB);
ArrayList<BufferedImage> downA=animUnitA.getDown();
ArrayList<BufferedImage> downB=animUnitB.getDown();
答案 1 :(得分:1)
从所有属性和方法中删除“static”一词,每当初始化某些内容为null时,将其初始化为“”。
示例:
而不是:
String xyz = null;
尝试:
String xyz = "";
答案 2 :(得分:-1)
好的,我刚做了一些测试,并且发现NullPointerException是关于AnimUnit类本身的一个实例,而不是ArrayLists的一个实例。无论如何,感谢所有人,即使问题根本没有关于阵列