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?

0

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

2
.getField("yellow"); 

"yellow" not "Yellow"

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.