The Java Developers Almanac 1.4


Order this book from Amazon.

   
Home > List of Packages > java.awt  [78 examples] > Colors  [4 examples]

e584. Retrieving a Predefined Color by Name

The Color class contains a number of predefined colors such as red and green. This example demonstrates how to retrieve one of these predefined colors using a string. For example, the predefined color java.awt.Color.red could be retrieved with the string "red".
    // Returns a Color based on 'colorName' which must be one of the predefined colors in
    // java.awt.Color. Returns null if colorName is not valid.
    public Color getColor(String colorName) {
        try {
            // Find the field and value of colorName
            Field field = Class.forName("java.awt.Color").getField(colorName);
            return (Color)field.get(null);
        } catch (Exception e) {
            return null;
        }
    }

 Related Examples
e582. Drawing with Color
e583. Drawing with a Gradient Color
e585. Converting Between RGB and HSB Colors

See also: Components    Containers    Cursors    Drawing    Events    Focus    Frames    GridBagLayout    Images    Shapes    Simulating Events    Text    The Screen   


© 2002 Addison-Wesley.