Get a Predefined Color by Name from java.awt.Color in Java

Description

The following code shows how to get a Predefined Color by Name from java.awt.Color.

Example


/*from w w w .j  a  va 2 s  . c  o m*/
import java.awt.Color;
import java.lang.reflect.Field;

public class Main {
  public static void main(String[] argv) throws Exception {
    System.out.println(getColor("blue"));
  }

  public static Color getColor(String colorName) {
    try {
      Field field = Class.forName("java.awt.Color").getField(colorName);
      return (Color) field.get(null);
    } catch (Exception e) {
      return null;
    }
  }
}

The code above generates the following result.





















Home »
  Java Tutorial »
    Reflection »




Annotation
Array
Class
Constructor
Field
Generics
Interface
Method
Modifier
Package
Proxy