Tom
Tom

Reputation: 15

Getting a Color from a String input

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.

Upvotes: 1

Views: 15975

Answers (5)

david72
david72

Reputation: 7297

Try using Color.parseColor(text);

Upvotes: 1

Jack
Jack

Reputation: 133567

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

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

color chooser

Upvotes: 3

Bala R
Bala R

Reputation: 108937

TRy

Color aColor   = (Color) Color.class.getField("white").get(null);

ALso,

See if the static method Color.decode() will serve your purpose.

Upvotes: 0

Naftali
Naftali

Reputation: 146302

you can always use a select box.

info on how to create a JComboBox

Upvotes: 0

nicolaas
nicolaas

Reputation: 1871

Wouldn't it be easier to just make a JComboBox or something alike?

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);

Upvotes: 1

Related Questions