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:
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.
You might create a class that stores both a String
representing the color name, as well as the Color
itself.
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.
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...
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;
}
}
You can try using String.valueOf(color.getRGB())