问题描述
我试图通过名字来获取颜色,我遇到,该建议使用 java.awt.getColor
。
I'm trying to get colors by name, and I came across Converting a String to Color in Java, which suggests using java.awt.getColor
.
我不知道是什么把它作为一个字符串传递虽然。以下
I can't work out what to pass it as a string though. The following
System.out.println( java.awt.Color.getColor( "black", Color.red ) );
打印出
java.awt.Color中的[R = 255,G = 0,B = 0]
即。它与默认的颜色在那里去。
i.e. it is going with the default color in there.
我已经把这个文本框,并试图替代capitalisations等文档是不是非常有帮助这里。任何人都可以提出来放什么魔法字符串?
I've put this in a text box, and tried alternative capitalisations etc. The docs aren't very helpful here. Can anyone suggest what magic strings to put in?
推荐答案
非公认的答案使用 Color.getColor
。这种方法从可以是或可以不是present系统属性的读取。你不应该使用这种方法。
The non-accepted answer uses Color.getColor
. This method reads from system properties which may or may not be present. You should not use this method.
相反,你应该使用upvoted反射法找到颜色
类的静态成员。无论是这一点,还是应该导入的字符串名称映射到RGB值,你自己的颜色数据库。
Instead, you should use the upvoted reflection method to find the static member of the Color
class. Either this, or you should import your own color database which maps string names to RGB values.
Color color;
try {
Field field = Color.class.getField("yellow");
color = (Color)field.get(null);
} catch (Exception e) {
color = null; // Not defined
}
这篇关于如何java.awt.Color.getColor(字符串colorName)工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!