java.awt.Color.getColor(String colorName) 是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3772098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 04:44:31  来源:igfitidea点击:

How does java.awt.Color.getColor(String colorName) work?

javacolorsawt

提问by mo-seph

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.

我正在尝试按名称获取颜色,我遇到了Converting a String to Color in Java,这建议使用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 ) );

prints out

打印出来

java.awt.Color[r=255,g=0,b=0]

java.awt.Color[r=255,g=0,b=0]

i.e. it is going with the default color in there.

即它在那里使用默认颜色。

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?

我已经把它放在一个文本框中,并尝试了替代大写等。这些文档在这里不是很有帮助。谁能建议放入什么魔法字符串?

采纳答案by Erick Robertson

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.

未接受的答案使用Color.getColor. 此方法从可能存在或可能不存在的系统属性中读取。你不应该使用这种方法。

Instead, you should use the upvoted reflection method to find the static member of the Colorclass. Either this, or you should import your own color database which maps string names to RGB values.

相反,您应该使用 upvoted 反射方法来查找类的静态成员Color。或者您应该导入您自己的颜色数据库,该数据库将字符串名称映射到 RGB 值。

Color color;
try {
    Field field = Color.class.getField("yellow");
    color = (Color)field.get(null);
} catch (Exception e) {
    color = null; // Not defined
}