2

Is there any way we can get color from String (like "White")?

Color color;
Field field = Class.forName("java.awt.Color").getField("Yellow");
color = (Color)field.get(null);

I tried Converting a String to Color in Java and it throws error . What "Field" belongs to? What package do I need to import for it?

Community
  • 1
  • 1
Pit Digger
  • 9,618
  • 23
  • 78
  • 122

2 Answers2

5

It is because the field that defines yellow is named YELLOW or yellow

You have an uppercase Y, which cannot be mapped to a Color. Instead, try:

Field field = Class.forName("java.awt.Color").getField("yellow");

Look at this class for all the fields contained within Color http://download.oracle.com/javase/6/docs/api/java/awt/Color.html

The code is just using reflection to access one of these fields.

The list of colours however is quite limited, so I don't know how much use this is likely to be for you.

Codemwnci
  • 54,176
  • 10
  • 96
  • 129
2
.getField("yellow"); 

"yellow" not "Yellow"

Costis Aivalis
  • 13,680
  • 3
  • 46
  • 47