Converting a String to Color in Java

In .NET you can achieve something like this:

Color yellowColor = Color.FromName("yellow");

Is there a way of doing this in Java without having to resort to reflection?

PS: I am not asking for alternative ways of storing/loading colors. I just want to know wherever it is possible to do this or not.


Use reflection to access the static member of the Color class.

Color color;
try {
    Field field = Class.forName("java.awt.Color").getField("yellow");
    color = (Color)field.get(null);
} catch (Exception e) {
    color = null; // Not defined
}

I tried something like this and it worked (at least for JavaFX)

String color = "red";
Color c = Color.web(color);
gc.setFill(color);
gc.fillOval(10, 10, 50, 40);

Why not make a custom class for this? I did this and it is working for me. NB: You will have to include this class in your package.

import java.awt.Color;

/**
 * A class to get the Color value from a string color name
 */
public class MyColor {
    private Color color;

 public MyColor(){
    color = Color.WHITE;
    }
/**
 * Get the color from a string name
 * 
 * @param col name of the color
 * @return White if no color is given, otherwise the Color object
 */
static Color getColor(String col) {
    switch (col.toLowerCase()) {
    case "black":
        color = Color.BLACK;
        break;
    case "blue":
        color = Color.BLUE;
        break;
    case "cyan":
        color = Color.CYAN;
        break;
    case "darkgray":
        color = Color.DARK_GRAY;
        break;
    case "gray":
        color = Color.GRAY;
        break;
    case "green":
        color = Color.GREEN;
        break;

    case "yellow":
        color = Color.YELLOW;
        break;
    case "lightgray":
        color = Color.LIGHT_GRAY;
        break;
    case "magneta":
        color = Color.MAGENTA;
        break;
    case "orange":
        color = Color.ORANGE;
        break;
    case "pink":
        color = Color.PINK;
        break;
    case "red":
        color = Color.RED;
        break;
    case "white":
        color = Color.WHITE;
        break;
        }
    return color;
    }
}

In some Container i just call it like this

public JPanel createStatusBar(){
    JPanel statusBar = new JPanel(layoutManager);
    statusBar.setBackgroundColr(MyColor.color("green"));
    // and other properties
    return statusBar;

Hope this helps.


I open sourced a little library named AWT Color Factory that provides methods for creating java.awt.Color instances from string representations.

These methods are the counterpart of static methods available in javafx.scene.paint.Color, such as Color.web(...) or Color.valueOf(...)

The library is extremely lightweight and does not depend on JavaFX.