我正在尝试将图像加载为枚举的一部分,但它引发异常,我找不到用try catch围绕它的方法,是否还有其他方法,还是不可能?

这是一些注释的代码,我正在使用Slick2d库。

    public enum Material {
//An enum of different materials, with different propierties and images

GRASS (5, false, null, true),

//Here I try to load an Image, but loading images throw an Exception, a Slick Exception I tried surronding it with try catch but its not working.
DIRT (5, false, new Image("res/Dirt.png"), true), 

WOOD (10, false, null, false), 

SNOW (1, false, null, false), 

ICE (1, false, null, false), 

LEAVES (1, false, null, false), 

STONE(15, false, null, false), 

COBBLESTONE(10, false, null, false), 

LOG(15, false, null, false),

AIR(1, false, null, false);


///variables
private int Resis;
private boolean traspasable;
private static Image I;
private boolean TreesCanGrow;

//getters
public int getResis(){
    return this.Resis;
}

public Image getTile(){
    return this.I;
}

public boolean isTraspasable(){

return this.traspasable;

}

public boolean getTreesCanGrow(){

return this.TreesCanGrow;

}


///constructor
private Material(int ExplosionResis, boolean isTraspasable, Image I, boolean TCG){  
this.Resis = ExplosionResis;
this.traspasable = isTraspasable;
this.TreesCanGrow = TCG;    
}


}

编辑:新的Contructor

///constructor
try {
    private Material(int ExplosionResis, boolean isTraspasable, String image, boolean TCG){ 
        this.Resis = ExplosionResis;
        this.traspasable = isTraspasable;
        this.TreesCanGrow = TCG;    
        this.I = new Image(image);
    }
}
catch (SlickException e) {
    e.printStackTrace();
}

}

===============>>#1 票数:3 已采纳

我不建议将可能失败的代码放在枚举构造函数中或作为枚举值声明的参数。 如果代码引发异常,则枚举类可能不会加载。

您可以尝试这样的事情:

/** An enum of different materials, with different properties and images. */
public enum Material {
  GRASS (5, false, null, true),

  DIRT (5, false, "res/Dirt.png", true), 

  ...

  AIR(1, false, null, false);


  private final int resis;
  private final boolean traspasable;
  private final String imagePath;
  private Image image;
  private final boolean treesCanGrow;

  private Material(int resis, boolean traspasable, String imagePath,
      boolean treesCanGrow) {  
    this.resis = resis;
    this.traspasable = traspasable;
    this.imagePath = imagePath;
    this.treesCanGrow = treesCanGrow;    
  }

  public synchronized Image getTile() throws SlickException {
    if (image == null && imagePath != null) {
      image = new Image(imagePath);
    }
    return image;
  }
}

但是,就我个人而言,我更喜欢枚举是不可变的,因此,如果这是我的代码,我会将Image的创建放在其他地方(也许放在延迟加载的Map<Material, Image>中)。

  ask by Zaphyk translate from so

未解决问题?本站智能推荐: