我正在为我的 AP 化学类(class)开发一个分子查看器。我为每个元素分配不同的颜色。例如,氢是白色的,碳是黑色的,氧是红色的。
当我调用要渲染的新元素时,它看起来像这样:
newAtom(x, y, z, color);
然后渲染原子。
因为有一百多个元素,所以有很多不同的颜色。
我应该为所有这些颜色创建单独的类吗?例如:
public class AtomColors {
// By atomic number
public final static Color H = new Color(1, 1, 1, 1);
public final static Color He = new Color(1, 0.5f, 1, 1);
public final static Color Li = new Color(0.5f, 1, 1, 1);
public final static Color Be = new Color(1, 1, 1, 0.5f);
}
我不确定是否有标准方法或这样做,以及哪种方法最有效。这就是我的问题。有更好的方法吗?
最佳答案
我认为Enum将最适合这里。枚举用于表示语言提供的结构中的相关常量。
您可以像下面这样表示颜色:
public enum ColorEnum {
H(1, 1, 1, 1),
He(1, 0.5f, 1, 1),
Li(0.5f, 1, 1, 1),
Be(1, 1, 1, 0.5f);
private final float cyan;
private final float magenta;
private final float yellow;
private final float black;
EnumTest(float cyan, float megenta, float yellow, float black) {
this.cyan = cyan;
this.megenta = megenta;
this.yellow = yellow;
this.black = black;
}
public float getCyan() { return cyan; }
public float getMegenta() { return megenta; }
public float getYellow() { return yellow; }
public float getBlack() { return black; }
public Color getColor() {
new Color(cyan, megenta, yellow, black);
}
}
像这样使用它
newAtom(x, y, z, ColorEnum.He);
我建议,要获取有关此主题的更多信息,请参阅
关于java - Java中保留 "reference variables"的标准,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18950965/