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; } }

Comments

1 Feb 2010 - 7:36am by Akhilesh Shende - Release Manager @ IBM (not verified)

To make it more elegant the line Field field = Class.forName("java.awt.Color").getField(colorName); can be also replaced with Field field = java.awt.Color.class.getField(colorName);

This is what my Architect suggested me :)

Post a comment

More information about formatting options

CAPTCHA
This question is for testing whether you are a human visitor and to prevent automated spam submissions.
Image CAPTCHA
Enter the characters shown in the image. Ignore spaces and be careful about upper and lower case.