4 Replies Latest reply: May 10, 2008 6:29 PM by 807591 RSS

    Convert String to Color object

    807591
      Hi, I was wondering if there is a way to convert a string into a color object.
      JTextArea text;
      String blue = "blue";
      
      Color col = Color.getColor(blue);
      
      text.setBackground(col);
      I found that example online but the Color object col returns a null value. Any ideas?
        • 1. Re: Convert String to Color object
          807591
          It could be done easily with either an enum class or with a Map<String, Color> object, though I'm sure that there are other and probably even better ways to do this.
          • 2. Re: Convert String to Color object
            807591
            Could you give an example or a link of where I could learn this?
            • 3. Re: Convert String to Color object
              807591
              terox13 wrote:
              Could you give an example or a link of where I could learn this?
              with a Map you could do something like so:
              import java.awt.Color;
              import java.util.HashMap;
              import java.util.Map;
              
              class Fubar1
              {
                  private Map<String, Color> colorMap = new HashMap<String, Color>();
                  
                  public Fubar1()
                  {
                      colorMap.put("black", Color.black);
                      colorMap.put("blue", Color.blue);
                      colorMap.put("red", Color.red);
                      colorMap.put("fubar", new Color(25, 125, 250));
                  }
                  
                  public void setColor()
                  {
                      String blue = "blue";
                       
                      Color col = Color.getColor(blue);
                      System.out.println(col);
                      
                      Color col2 = colorMap.get(blue);
                      System.out.println(col2);
                  }
                  
                  public static void main(String[] args)
                  {
                      Fubar1 f1 = new Fubar1();
                      f1.setColor();
                  }
              }
              • 4. Re: Convert String to Color object
                807591
                Awesome, thank you!