【发布时间】:2013-02-27 05:49:36
【问题描述】:
我在创建对象数组时遇到问题,但是当我尝试向它解决某些问题时得到java.lang.NullPointerException。
这是有问题的班级。
public class Blocks {
public static Block[] b = new Block[8];
public Blocks() throws IOException {
new Air (b[0]);
new Stone(b[1]);
new Grass(b[2]);
new Dirt (b[3]);
}
这是类 Block。
public class Block {
private Texture Texture = null;
private int S = World.BLOCK_SIZE;
private boolean hasTexture = true;
private String texturePath = null;
public void setTexture(String path) throws IOException {
this.texturePath = path;
Texture = TextureLoader.getTexture("PNG", new FileInputStream(new File(path)));
}
public void draw(int Xa, int Ya) {
GL11.glTranslatef(Xa, Ya, 0);
//GL11.glRotatef(0, 0, 1, 0);
//GL11.glRotatef(0, 1, 0, 0);
if(hasTexture) {
Texture.bind();
GL11.glBegin(GL11.GL_QUADS);
GL11.glColor3f(0.5f, 0.5f, 1);
//GL11.glNormal3f(0, 0, 1);
GL11.glTexCoord2f(0, 0);
GL11.glVertex2f(0, 0);
GL11.glTexCoord2f(0, 1);
GL11.glVertex2f(0, S);
GL11.glTexCoord2f(1, 1);
GL11.glVertex2f(S, S);
GL11.glTexCoord2f(1, 0);
GL11.glVertex2f(S, 0);
GL11.glEnd();
}
}
void hasTexture(boolean b) {
this.hasTexture = b;
}
}
如果我需要提供更多信息/代码,请告诉我
【问题讨论】:
-
您应该提供错误信息(错误信息、行、堆栈跟踪)
-
我认为获取纹理有问题:Texture = TextureLoader.getTexture("PNG", new FileInputStream(new File(path)));
-
texture 为 null,当您尝试使用 null 对象时,您会得到 NullPointerException
-
对静态字段使用静态初始化块,或静态惰性 getter。并将对象正确分配给您的数组: b[0] = new Block()
-
否决这一点并没有真正的帮助。是的,它可以改进,但没有必要在这个问题上大发雷霆。