Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a String to Color in Java

Tags:

java

colors

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.

like image 808
devoured elysium Avatar asked May 18 '10 01:05

devoured elysium


People also ask

How do you change a string to a color in Java?

In . NET you can achieve something like this: Color yellowColor = Color. FromName("yellow");

Which method do you use to add a new string to a set named color?

String color="RED" int c1=parseInt(color) new Color(c1);


2 Answers

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
}
like image 104
ZZ Coder Avatar answered Sep 18 '22 13:09

ZZ Coder


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);
like image 37
randy costanza Avatar answered Sep 20 '22 13:09

randy costanza