如何在 Java 中打印颜色的字符串表示

如何在 Java 中打印颜色的字符串表示

问题描述:

我有一个大小为 n 的颜色数组.在我的程序中,团队的数量总是

I have an array of colours of size n. In my program, the number of teams is always <= n, and I need to assign each team a unique color. This is my color array:

private static Color[] TEAM_COLORS = {Color.BLUE, Color.RED, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};

当我在控制台中打印有关玩家的信息时,我想打印与他们相关联的颜色.当我打印颜色时,我得到 ​​p>

When I print information about the players in the console, I want to print what color is associated with them. When I print the color, I get

java.awt.Color[r=...,g=...,b=...]. 

我知道这就是 Java 打印颜色的方式.我想知道是否有办法代替打印蓝色、红色等(因此是预定义的颜色字符串).

I understand that this is how Java prints colours. I was wondering if there was a way to instead print BLUE, RED, etc. (so the pre-defined color string).

通过将名称也添加到枚举来扩展 @Jon_Skeet 回复.

Extending @Jon_Skeet reply by adding name also to the enum.

public enum NamedColor {
  BLUE(Color.BLUE, "Blue"),
  RED(Color.RED, "Red"),
  ...;

  private final Color awtColor;
  private final String colorName;

  private NamedColor(Color awtColor, String name) {
    this.awtColor = awtColor;
    this.colorName = name;
  }

  public Color getAwtColor() {
    return awtColor;
  }

  public String getColorName() {
    return colorName;
  }
}

注意:如果对此投票,请也投票@Jon_Skeet 回复,因为它是那个的扩展......

NOTE: IF voting this pls vote @Jon_Skeet reply too as it is extension of that...