java 从字符串输入获取颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5822384/
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
Getting a Color from a String input
提问by Tom
I am making an application where at some point i need the user to select a color, but as to not just have 50 radioButtons, I was wondering if it is possible to actually get the color they want from a textfield or something.
我正在制作一个应用程序,在某些时候我需要用户选择一种颜色,但不仅仅是有 50 个单选按钮,我想知道是否有可能从文本字段或其他东西中实际获得他们想要的颜色。
采纳答案by nicolaas
Wouldn't it be easier to just make a JComboBox or something alike?
制作 JComboBox 或类似的东西不是更容易吗?
But to answer your question: Yes it is possible. I'll give a piece of code that you could use as a start to get you going (assuming you still want the string to color)
但是要回答您的问题:是的,这是可能的。我将给出一段代码,您可以将其用作开始(假设您仍然希望字符串着色)
String text = "red";
Color color;
Field field = Class.forName("java.awt.Color").getField(text.toLowerCase()); // toLowerCase because the color fields are RED or red, not Red
color = (Color)field.get(null);
回答by Hyman
回答by david72
Try using Color.parseColor(text);
尝试使用 Color.parseColor(text);
回答by Naftali aka Neal
回答by Bala R
TRy
尝试
Color aColor = (Color) Color.class.getField("white").get(null);
ALso,
还,
See if the static method Color.decode()will serve your purpose.
看看静态方法Color.decode()是否能达到你的目的。