LEARN HOW TO CREATE HTML-LIKE COLORS IN JAVA
While HTML uses a hexadecimal scheme to specify colors, Java provides
both constants and integer constructors of the color class. Java color
is
dealt with by java.awt.Color, but it doesn't have an easy-to-use
HTML-like
application program interface (API). Colors are obtained by using:
Color.blue
or by making a new color with:
new Color(0,0,255)
However, there aren't many constants, so most colors need to be made
via
integer constructors. HTML-based color can easily be translated to Java
by using hexadecimal-based integers. For the color blue, enter the
following:
new Color(0,0,0xff)
For pale yellow, use:
new Color(0xf5,0xef,0xd1)
Another way to turn an HTML color, such as #fe432b, into a
java.awt.Color object is by using a simple getColor method. Here's an
example:
package com.generationjava.awt;
import java.awt.Color;
public class ColorW {
/**
* Given a html-like color such as #bbac33, turns it
* into a java.awt.Color. The # on the front is optional.
*/
static public Color getColor(String color) {
if(color.charAt(0) == '#') {
color = color.substring(1);
}
if(color.length() != 6) {
return null;
}
try {
int r = Integer.parseInt(color.substring(0,2), 16);
int g = Integer.parseInt(color.substring(2,4), 16);
int b = Integer.parseInt(color.substring(4), 16);
return new Color(r, g, b);
} catch(NumberFormatException nfe) {
return null;
}
}
}
----------------------------------------