Hello,

I have a question, in my program I want to read a text field then to convert it to Color, How Can I do this ?

I try this, but I didn't know if this is right :

String colorString = getCarTextButtons()[3].getText();
Color color = Color.getColor(colorString);

No, I don't think you can do that.
I think you will need to create a Hashtable with all the valid String color names as the keys and the actual Color instances as the values. Then you can simply get(...) the Color instance associated with the String you have got from the UI.

thank u, but How can I get the clor values, Are u have a link that could be help me ?

thanks again : )

The standard colors have public constants defined for them in the Color class, ie Color.BLACK, Color.PINK etc etc, so you could create the Hashtable with keys like "black", "pink" etc and values as above.

Hashtable<String, Color> lookup = new Hashtable<String, Color>();
lookup.put("black", Color.BLACK);
...
Color c = lookup.get(myUIthing.getText().toLowerCase());

Create your color enumerator.

import java.awt.*;
import java.awt.color.*;
enum C
{
   red (Color.RED),blue (Color.BLUE),green (Color.GREEN);

   private final Color color;
   //Constructor
   C(Color color) { this.color=color;}
   
   public static Color get(String name){
      for(C a:C.values()) {
         if(a.toString().equals(name))
            return a.color; 
      }
      return null;
   }
}
class color
{
public static void main(String []args)
 {
    System.out.println(C.get("red"));
    System.out.println(C.get("blue"));
    System.out.println(C.get("Green")); //null
  }
}

Create your color enumerator.

That's a good idea too.
ps The get (...) method here seems to be a duplicate of the built-in valueOf(String name) method - or have I missed something?

Thank you :)

I do what James tell me, And it's do correct without problems.

thank you james & adatapost

ps The get (...) method here seems to be a duplicate of the built-in valueOf(String name) method - or have I missed something?

I think that too !!!

Hi JC,
Thanks for reply.
I don't think that a get() is duplicate of valueOf. valueOf method return enum type and it throws an IllegalArgumentException, if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type.

... I don't think that a get() is duplicate of valueOf. valueOf method return enum type and it throws an IllegalArgumentException, if the specified enum type has no constant with the specified name, or the specified class object does not represent an enum type.

Yes, I agree. Thanks for pointing that out. I'd fallen into the trap of confusing the enum values with the Colors themselves.

titosd: adatapost's solution really is better than mine, especially if the list of valid colors isn't going to change.

Comments
There is no distance!
This article has been dead for over six months. Start a new discussion instead.