0

Using Java, how do I convert a human readable color name into a three-element integer array?

For example, I have a color represented by:

int[] RGB_COLOR = {128,25,25};

And I want to be able to convert the static value Color.BLUE into a three-element integer array that is similar to the one above. Is this possible or do I have to hack my way around this?

4 Answers 4

4

Do you mean like this...

Color c = Color.BLUE;
int[] RGB = { c.getRed(), c.getGreen(), c.getBlue() };

To convert a colour name to a Color you can use reflections, provided its own of the built in colours. If you want more colours you would need to use a map.

public static Color colorOf(String color) {
    try {
        return (Color) Color.class.getDeclaredField(color).get(null);
    } catch(Exception notAvailable) {
        return null; // ??
    }
}
Sign up to request clarification or add additional context in comments.

3 Comments

This almost answers my question, as it answers my int[] question but it doesn't answer how to convert the string "BLUE" into the static Color.BLUE . There is no method called 'new Color("BLUE")'.
I have added an option for built-in colours. However you are likely to want a more extensive list of your own. You could use a properties file for example.
Thanks to you all. This works great for me. All I needed was access to the default colors in the Color class.
1

Just use the getGreen(), getRed(), getBlue() methods of the Color class

Comments

1

scroll down on the doc you linked

Color c = //...;
int[] color = {c.getRed(),c.getGreen(),c.getBlue()};

Comments

0

The simplest way to get a Color object from a String would be to create a Map<String, Color> mapping the valid String color names to Color objects.

Map<String, Color> map = new HashMap<String, Color>();
map.put("BLUE", Color.BLUE);
// etc.

Color color = map.get(someString);

Also, I'd recomment not storing the RGB values in an int[3] unless you really need that because some 3rd party code expects it or something. Just using the Color class is much more appropriate in general.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.