Java Color from String "Yellow"
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 C开发者_如何学Pythononverting a String to Color in Java and it throws error . What "Field" belongs to? What package do I need to import for it?
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.
.getField("yellow");
"yellow" not "Yellow"
精彩评论