1
votes

I have a java code that returns decimal values as shown below

 [1.0, 0.0, 0.0] for Red  
 [0.0, 1.0, 0.0] for Green 

the first value denotes the color code for Red, the second value denotes color code for Green and the third value denotes Color code for Blue.

Is there any way we can convert these RGB values into the respective color in java?

1
Perhaps you're looking for this constructor?sgbj

1 Answers

3
votes

There are an example to return the color name which depend on using Reflection to get the name of the color (java.awt.Color)

public static String getNameReflection(Color colorParam) {
        try {
            //first read all fields in array
            Field[] field = Class.forName("java.awt.Color").getDeclaredFields();
            for (Field f : field) {
                String colorName = f.getName();
                Class<?> t = f.getType();
                if (t == java.awt.Color.class) {
                    Color defined = (Color) f.get(null);
                    if (defined.equals(colorParam)) {
                        System.out.println(colorName);
                        return colorName.toUpperCase();
                    }
                }
            }
        } catch (Exception e) {
            System.out.println("Error... " + e.toString());
        }
        return "NO_MATCH";
    }

and in the main

        Color colr = new Color(1.0f, 0.0f, 0.0f);
        Main m = new Main();
        m.getNameReflection(colr);
    }

You have to know that :"java.awt.Color" defined this colors:

white
WHITE
lightGray
LIGHT_GRAY
gray
GRAY
darkGray
DARK_GRAY
black
BLACK
red
RED
pink
PINK
orange
ORANGE
yellow
YELLOW
green
GREEN
magenta
MAGENTA
cyan
CYAN
blue
BLUE