Matt Clark Matt Clark - 2 years ago 107
Java Question

getting a color by name in java

I am working with an object model that contains a


import java.awt.Color;

public class MyObject {

private String color;

public void setColor( Color c ) ...
public Color getColor() ...


In the response of a json query, I am left with a physical name of a color


I know that the Color object has statics i.e.;

Is there any way to decode actual color names into Color objects? Or would I need to manually map the strings to rgb values myself?

I am looking for something that should be the output of this

Color c = new Color("blue");

which does not work

Answer Source

If your names correspond to those of Java's constants, you can use reflection to map them:

public static Color getColorByName(String name) {
    try {
        return (Color)Color.class.getField(name.toUpperCase()).get(null);
    } catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException | SecurityException e) {
        return null;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download