如何在 Java 中打印颜色的字符串表示 [英] How To Print String representation of Color in Java

查看:47
本文介绍了如何在 Java 中打印颜色的字符串表示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个大小为 n 的颜色数组.在我的程序中,团队的数量总是 <= 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};

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

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

这篇关于如何在 Java 中打印颜色的字符串表示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆