编码:

public class EmptyTile extends TileEntity{ //error on this brace
    try{
        defaultTexture=TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png")); //defaultTexture is created in the class that this class extends
    }catch (IOException e) {
        e.printStackTrace();
    } //also an error on this brace
    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
    }
}


我也尝试过将try / catch语句移至EmptyTile构造函数,但它需要在调用超级构造函数之前初始化默认纹理,这显然是不允许的。

我也尝试过在此类的父类中使defaultTexture变量既静态又常规。

最佳答案

您不能将try/catch放在类级别,只能放在构造函数,方法或初始化程序块中。这就是导致错误报告的原因。假设defaultTexture是属性,请尝试在构造函数内部移动代码:

public class EmptyTile extends TileEntity {

    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
        try {
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}


但是,如果defaultTexture是静态属性,则使用静态初始化程序块:

public class EmptyTile extends TileEntity {

    static {
        try {
            defaultTexture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream("stone.png"));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public EmptyTile(int x, int y, int height, int width, Texture texture) {
        super(x, y, height, width, texture);
    }

}

10-06 10:07