java - Java中保留 "reference variables"的标准

标签 java

我正在为我的 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/

相关文章:

java - 如何在Android的mapbox sdk中绘制弯曲的折线

带有 java.io 包的 Java react 器模式

java - 如何使用 JProfiler 在 Java 中查找内存泄漏?

java - JComponents (Swing) 的二维网格

java - 将年份添加到 Date 类的随机日期

java - 从配置单元 Metastore 数据库中删除锁定文件

java spring 入门问题

java.lang.ClassCastException : java. lang.String 无法转换为 [Ljava.lang.Object; - 使用 hibernate 从数据库中获取查询

java - 从附加的 OnPreDrawListener 对象中获取 ViewTreeObserver 对象

Java 程序逻辑错误。 IF..部分不工作/执行