AlexC
AlexC

Reputation: 402

Getting a string representing the color name from an instance of Color

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.

Upvotes: 0

Views: 1842

Answers (2)

Pshemo
Pshemo

Reputation: 124215

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

Upvotes: 2

Tareq Salah
Tareq Salah

Reputation: 3718

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)

Upvotes: 1

Related Questions