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

发布于 2025-01-03 21:22:24 字数 388 浏览 1 评论 0原文

我有一个大小为 n 的颜色数组。在我的程序中,团队的数量始终<= n,并且我需要为每个团队分配唯一的颜色。这是我的颜色数组:

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

当我在控制台中打印有关玩家的信息时,我想打印与他们关联的颜色。当我打印颜色时,我明白

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

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

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};

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=...]. 

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).

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

终弃我 2025-01-10 21:22:24

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

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 回复,因为它是该内容的延伸...

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;
  }
}

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

染火枫林 2025-01-10 21:22:24

一种选择是创建一个 NamedColor 枚举:

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

    private final Color awtColor;

    private NamedColor(Color awtColor) {
        this.awtColor = awtColor;
    }

    public Color getAwtColor() {
        return awtColor;
    }
}

然后将 TEAM_COLORS 数组设置为 NamedColor 值数组,而不是 Color 值,并在需要时获取 AWT 颜色。枚举的默认 toString 实现是它的名称。

另一种选择是创建您自己的 Map 并在需要颜色的字符串表示形式时查阅。

One option would be to create a NamedColor enum:

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

    private final Color awtColor;

    private NamedColor(Color awtColor) {
        this.awtColor = awtColor;
    }

    public Color getAwtColor() {
        return awtColor;
    }
}

You'd then make your TEAM_COLORS array an array of NamedColor values instead of Color values, and fetch the AWT color when you need it. The default toString implementation of an enum is its name.

Another alternative would be to create your own Map<Color, String> and consult that when you need the string representation for a color.

勿忘心安 2025-01-10 21:22:24

以下是基于反射的方法:

public static String getColorName(Color c) {
    for (Field f : Color.class.getFields()) {
        try {
            if (f.getType() == Color.class && f.get(null).equals(c)) {
                return f.getName();
            }
        } catch (java.lang.IllegalAccessException e) {
            // it should never get to here
        } 
    }
    return "unknown";
}

示例:

getColorName(Color.BLACK); // black
getColorName(Color.BLUE); // blue
getColorName(new Color(0,1,2)); // unknown

演示:http://ideone.com/6cIBD


java.awt.Color,即:白色、浅灰色、灰色、深灰色、黑色、红色、粉色、橙色、黄色、绿色、洋红色、青色和蓝色。

Here's a Reflection-based approach:

public static String getColorName(Color c) {
    for (Field f : Color.class.getFields()) {
        try {
            if (f.getType() == Color.class && f.get(null).equals(c)) {
                return f.getName();
            }
        } catch (java.lang.IllegalAccessException e) {
            // it should never get to here
        } 
    }
    return "unknown";
}

Examples:

getColorName(Color.BLACK); // black
getColorName(Color.BLUE); // blue
getColorName(new Color(0,1,2)); // unknown

Demo: http://ideone.com/6cIBD


This will only work with colors defined as fields in java.awt.Color, namely: white, light gray, gray, dark gray, black, red, pink, orange, yellow, green, magenta, cyan and blue.

无戏配角 2025-01-10 21:22:24

您可以创建一个类来存储表示颜色名称的 String 以及 Color 本身。

You might create a class that stores both a String representing the color name, as well as the Color itself.

朱染 2025-01-10 21:22:24

如果您希望将 NamedColor 用作 java.awt.Color 并且您没有很多颜色,则可以扩展它并存储名称。

public class NamedColor extends java.awt.Color {

    private String name;

    public NamedColor(String name, java.awt.Color c) {
        super(c.getRGB());
        this.name = name;
    }

    public String toString() {
        return name;
    }
}

If you want your NamedColor to be used as a java.awt.Color and you don't have many colors you can extend it and store the name.

public class NamedColor extends java.awt.Color {

    private String name;

    public NamedColor(String name, java.awt.Color c) {
        super(c.getRGB());
        this.name = name;
    }

    public String toString() {
        return name;
    }
}
日暮斜阳 2025-01-10 21:22:24
  public static String colorToString(Color c) {
    if (c == null)  return "NullColor";
    for (var f : Color.class.getFields()) {
      if (f.getType() != Color.class)  continue;
      try {
        if (c.equals(f.get(null)))  return f.getName().toLowerCase();
      } catch (java.lang.IllegalAccessException e) {
        // Ignore. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)
      }
    }
    return c.toString();
  }
  public static String colorToString(Color c) {
    if (c == null)  return "NullColor";
    for (var f : Color.class.getFields()) {
      if (f.getType() != Color.class)  continue;
      try {
        if (c.equals(f.get(null)))  return f.getName().toLowerCase();
      } catch (java.lang.IllegalAccessException e) {
        // Ignore. https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/lang/reflect/Field.html#get(java.lang.Object)
      }
    }
    return c.toString();
  }
丶情人眼里出诗心の 2025-01-10 21:22:24

您可以尝试使用
String.valueOf(color.getRGB())

You can try using
String.valueOf(color.getRGB())

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文