java - 为什么我在牙套上出现错误?

标签 java lwjgl slick2d

代码:

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 构造函数,但它需要在调用 super 构造函数之前初始化默认纹理,这显然是不允许的。

我还尝试在此类的父类中将 defaultTexture 变量设置为静态变量和常规变量。

最佳答案

您不能将 try/catch 放置在类级别,只能放置在构造函数、方法或初始值设定项 block 内。这就是导致报告错误的原因。尝试将代码移至构造函数内,假设 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 是静态属性,则使用静态初始化 block :

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);
    }

}

关于java - 为什么我在牙套上出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19883157/

相关文章:

java - 在 Mac 上许可软件的方法(基于文件/离线)

java - 从java中的文本文件输入创建ArrayList中的对象

java - 创建的对象粘在屏幕上并且不随 map 移动

java - Slick2d 背景

java - GPU 上的内存大小分配 - opengl 纹理加载问题

java - 慢速角度旋转

java - 了解 classes.dex 中的 Java 代码链接

java - 在Java中设置类路径

java - Libgdx - 帧缓冲区的纹理渲染到屏幕时的不同大小

java - LWJGL 2.9.0 GL20.glUniformMatrix4 导致随机卡顿