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

a をクラス レベルに置くことはできません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);
    }

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

コンストラクターで使用する場合TileEntitydefaultTexture、コンストラクターを変更して渡せるようにする必要があることに注意してください。

于 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 に答える