我有一个存储颜色名称的字符串。通过这个变量的帮助,我需要更改面板背景。怎么办?
答案 0 :(得分:2)
创建包含颜色的String名称和实际Color对象的Map。
编辑:
注意到另外两个答案建议使用getColor(...)方法。这不仅仅是神奇地工作,您需要在系统属性中定义颜色。我从未使用过系统属性,但我相信你需要在启动JVM时设置它们。
答案 1 :(得分:1)
如果颜色只是java支持的颜色,您可以执行以下操作:
private Color getColorByName(String colorName) {
Field[] colorFields = Color.class.getDeclaredFields();
for (Field field : colorFields) {
if (field.getName().equals(colorName.toUpper())) {
//check that this is in fact a static field,
//to make sure it is one of the colors you are looking for
int modifiers = field.getModifiers();
if ((Modifiers.STATIC & modifiers != 0)
&& (Modifiers.PUBLIC & modifiers != 0)) {
try{
return (Color)field.getValue(null);
} catch (FieldNotFoundException ex) {
//Maybe put some additional handling in here if you need it
}
}
}
}
//or return a default color
return null;
}
一些注意事项:
制作更有意义 其他人提到的彩色地图 上面的人。
最好的是 如果不同的系统发送给您 实际值 - 比如说rgb值 int或0.0-1.0双格式。然后 你可以一直给他们 适当的回应。
我的建议,如果你必须使用颜色名称,那就是它们会给你一组你必须支持的名字,并且你有一个错误条件 - 默认颜色,null或抛出异常。
希望这有帮助。