如何在 Java 中打印颜色的字符串表示
我有一个大小为 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
通过将名称也添加到枚举来扩展@Jon_Skeet回复。
注意:如果对此进行投票,请也投票@Jon_Skeet 回复,因为它是该内容的延伸...
Extending @Jon_Skeet reply by adding name also to the enum.
NOTE: IF voting this pls vote @Jon_Skeet reply too as it is extension of that...
一种选择是创建一个
NamedColor
枚举:然后将
TEAM_COLORS
数组设置为NamedColor
值数组,而不是Color
值,并在需要时获取 AWT 颜色。枚举的默认toString
实现是它的名称。另一种选择是创建您自己的
Map
并在需要颜色的字符串表示形式时查阅。One option would be to create a
NamedColor
enum:You'd then make your
TEAM_COLORS
array an array ofNamedColor
values instead ofColor
values, and fetch the AWT color when you need it. The defaulttoString
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.以下是基于反射的方法:
示例:
演示:http://ideone.com/6cIBD
于
java.awt.Color
,即:白色、浅灰色、灰色、深灰色、黑色、红色、粉色、橙色、黄色、绿色、洋红色、青色和蓝色。Here's a Reflection-based approach:
Examples:
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.您可以创建一个类来存储表示颜色名称的
String
以及Color
本身。You might create a class that stores both a
String
representing the color name, as well as theColor
itself.如果您希望将 NamedColor 用作 java.awt.Color 并且您没有很多颜色,则可以扩展它并存储名称。
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.
您可以尝试使用
String.valueOf(color.getRGB())
You can try using
String.valueOf(color.getRGB())