[ Back | Previous | Next ]

Converting a String to a Color.

Package:
java.awt.*
Product:
JDK
Release:
1.0.2
Related Links:
Color
Cursor
FileDialog
Font
FontMetrics
Frame
general
Image
LayoutManager
Menu
ScrollPane
Comment:
The easy way is to convert the string as an int with radix 16. 
The following code snapshots :

String to Color:

String scolor = "ffffbb";
Color bordercolor = new Color( Integer.parseInt( scolor ), 16 ) );
Especially if you want to use both HTML color format and 24 bit integer format in applet parameters it might be handy to implement the following code:

//
// ColorUtil.java
//
package nl.rotterdam.port.awt;

import java.awt.*;

/**
 * This clas extends the color class and 
 * add features like valueOf to the color class
 * to convert HTML color format to a Color object.
 */
public class ColorPlus  {

  /** 
   * Parses the specified Color as a string. 
   * @param representation of the color as a 24-bit integer, the format of the string can be either htmlcolor #xxxxxx or xxxxxx.
   * @return the new color.
   * @exception NumberFormatException if the format of the string does not comply with rules or illegal charater for the 24-bit integer as a string.
   */
  public static Color parse(String nm ) throws NumberFormatException {
    if ( nm.startsWith("#") ) {
      nm = nm.substring(1);
    }
    nm = nm.toLowerCase();
    if (nm.length() > 6) {
      throw new NumberFormatException("nm is not a 24 bit representation of the color, string too long"); 
    }
    System.out.println("nm=" + nm );
    Color color = new Color( Integer.parseInt( nm , 16 ) );
    return color;
  }

  
}
1