3

Possible Duplicate:
How To Print String representation of Color in Java

I have a method called getColor() that returns a color (like Color.BLACK). Is there a way to convert getColor() into a string of its name?

String test = getColor().toString(); 

If getColor() returns Color.BLACK, then

String test = Color.BLACK.toString();
System.out.println(test);

OUTPUT

java.awt.Color[r=0,g=0,b=0]
Community
  • 1
  • 1
Dog
  • 595
  • 3
  • 11
  • 20

3 Answers3

4

Create a custom map of color names against their color codes. Once you have retrieve the color code, get the string using your custom map.

       Map<Color, String> colorMap = new HashMap<Color, String>();
       colorMap.put(Color.BLACK, "Black"),   
       colorMap.put(Color.RED, "Red"),  
       .......

Once you have your color, use below to get the color name:

      Color myColor = getColor();
      String colorName = colorMap.get(myColor);
Yogendra Singh
  • 33,927
  • 6
  • 63
  • 73
3

toString() can never reproduce the original name of the variable that was used to store that instance (because there can be more than one containing that instance).

One way would be to manually compare the Color instance:

Color theColor = getColor()
String colorName = null;
if (Color.BLACK.equals(theColor)) 
{
  colorName = "BLACK";
} 
else if (Color.WHITE.equals(theColor)) 
{
  colorName = "WHITE";
}
...
System.out.println(colorName);
1

No.

Color.BLACK is one of a large range of colors, and maps to RGB values of 0, 0, 0.

If you were to have an RGB of 0, 0, 1 - almost black, with just a little blue - what color would that be? How about off-green? Or yellow with just a little extra red?

That's why there's no way to convert a raw color back to a string again; because there are far more colors which are represented by the different RGB values than just the ones which are represented by strings.

If you don't want to go down the NamedColor enum route mentioned in comments, an easy solution might be to use reflection to go over the static Color fields of the Color class, and add each field name into a hashmap with its associated color as the key, removing one of the upper or lower-case duplicates since it has both. You could then look to see if your color is there.

Lunivore
  • 17,277
  • 4
  • 47
  • 92