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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 12:57:01  来源:igfitidea点击:

Getting a Color from a String input

java

提问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

Why don't you use a JColorChooserthat is a standard Swing component?

为什么不使用JColorChooser标准 Swing 组件?

You can read a tutorial herebut it is quite straightforward to use, as every Swing dialog, the result is something like:

您可以在此处阅读教程但使用起来非常简单,因为每个 Swing 对话框的结果都类似于:

color chooser

颜色选择器

回答by david72

Try using Color.parseColor(text);

尝试使用 Color.parseColor(text);

回答by Naftali aka Neal

you can always use a select box.

您始终可以使用选择框。

info on how to create a JComboBox

关于如何创建 JComboBox 的信息

回答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()是否能达到你的目的。