0

How can I get a String representing name of the color (and not the awt RGB code) from an instance of the Color class?

For example I have

Color black=Color.BLACK;

and I want to get the string "Black".

I know this should be possible using Java reflection, but I'm not very familiar with it. Thank you.

AlexC
  • 402
  • 1
  • 4
  • 11
  • It might help you [java.awt.color to java.lang.string conversion](http://stackoverflow.com/questions/6717765/java-awt-color-to-java-lang-string-conversion) – Braj Jun 15 '14 at 18:02

2 Answers2

2

Color class has only few non-static fields which are

name      | type         
----------+---------------
value     | int 
frgbvalue | float[] 
fvalue    | float[] 
falpha    | float 
cs        | java.awt.color.ColorSpace 

and none of this fields store color name. Also it doesn't have any method which would check if color you are using is equal to one of its predefined ones and stored in static references like

public final static Color black = new Color(0, 0, 0);
public final static Color BLACK = black;

But nothing stops you from implementing your own method which will do it for you. Such method can look like

public static Optional<String> colorName(Color c) {
    for (Field f : Color.class.getDeclaredFields()) {
        //we want to test only fields of type Color
        if (f.getType().equals(Color.class))
            try {
                if (f.get(null).equals(c))
                    return Optional.of(f.getName().toLowerCase());
            } catch (IllegalArgumentException | IllegalAccessException e) {
                // shouldn't not be thrown, but just in case print its stacktrace
                e.printStackTrace();
            }
    }
    return Optional.empty();
}

Usage example

System.out.println(colorName(Color.BLACK).orElse("no name found"));
System.out.println(colorName(new Color(10, 20, 30)).orElse("no name found"));
System.out.println(colorName(null).orElse("no name found"));

Output:

black
no name found
no name found
Pshemo
  • 122,468
  • 25
  • 185
  • 269
1

You can use predefined map <Color, String> to insert some predfined colors on it and then use it to get the name

HashMap<Color,String> hm = new HashMap <Color,String>();
hm.put(Color.BLACK,"Black");
.
.
.
hm.get(Color.BLACK)
Tareq Salah
  • 3,720
  • 4
  • 34
  • 48