0

编码:

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 变量设为静态和常规变量。

4

3 回答 3

2

您不能将 atry/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);
    }

}
于 2013-11-09T21:16:36.743 回答
0
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")); //defaultTexture is created in the class that this class extends
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

请注意,如果在构造函数中TileEntity使用defaultTexture,则必须修改构造函数以允许传入。

于 2013-11-09T21:14:42.970 回答
0

如果你想在构造函数之外做,你可以把它放在一个实例初始化块中:

public class EmptyTile extends TileEntity {

    // empty brace is instance initializer
    {
        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);
    }
}
于 2013-11-09T21:52:16.880 回答