3 Replies Latest reply: May 24, 2012 12:54 AM by Sreram RSS

    Getting java.awt.Color object from String

    Sreram
      Had googled this and got solutions like Color.getColor("BLACK"), and Color.class.getField("BLACK").get(null) - with try catch block... Yet am not able to get the color object.. I always get null in the first case and exception in second case... Any ideas?

      Sreram
        • 1. Re: Getting java.awt.Color object from String
          DarrylBurke
          Post what you tried, in the form of a SSCCE (Short, Self Contained, Correct (Compilable), Example).

          Don't forget to use code tags, or nobody will bother to read the code.

          db
          • 2. Re: Getting java.awt.Color object from String
            Sreram
            Hmm. Thanks for your reply. Here is the code snippet you asked for.
                public Color getColor(String strcolor) {
                    Color color = Color.ORANGE;
                    color = Color.getColor(strcolor.toUpperCase()); //returns null here...
                    if(color == null){
                        try {
                            color = Color.class.getField(strcolor.toUpperCase()).get(null);
                        } catch (Exception ex) {
                            ex.printStackTrace(); //Always getting java.lang.NoSuchFieldException:  {passed color name in this case RED}
                        }
                    }
                    if(color == null){
                        color = Color.ORANGE; //If color is null return default ORANGE.
                    }
                    return color; //Always returns ORANGE here...
                }
                
                public void printUserColor(){
                    System.out.println(getColor("RED"));
                }
            Also saw an interesting javadoc on Toolkit, a method called getDesktopProperty(String propertyName)... But not sure whether this can be used to get the System Color...
            • 3. Re: Getting java.awt.Color object from String
              Sreram
              Sorry again... I didn't trim the string am sending as argument. Color.class.getField is working fine now.. Thanks...

              Sreram