Java Color from String “Yellow”

让人想犯罪 __ 提交于 2019-12-11 07:01:26

问题


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?


回答1:


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.




回答2:


.getField("yellow"); 

"yellow" not "Yellow"



来源:https://stackoverflow.com/questions/5519617/java-color-from-string-yellow

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!