mercredi 25 mars 2015

Getting string value of color from Color.getHSBColor

Good day to all,


I am using a code provided by Mr. Komplot in creating random color in Java.


Here is his code:



int R = (int)(Math.random()*256);
int G = (int)(Math.random()*256);
int B= (int)(Math.random()*256);
Color color = new Color(R, G, B); //random color, but can be bright or dull

//to get rainbow, pastel colors
Random random = new Random();
final float hue = random.nextFloat();
final float saturation = 0.9f;//1.0 for brilliant, 0.0 for dull
final float luminance = 1.0f; //1.0 for brighter, 0.0 for black
color = Color.getHSBColor(hue, saturation, luminance);


My program creates a pie graph based on a given data set, and for every slice of the pie graph corresponds to a certain color. Each color is defined using the default colors provided by java.awt.Color. Knowing that there could be instances wherein the number of slices would exceed the default colors provided by java.awt.Color, this kind of solution would not be efficient at all. That is why, I have used Mr. Komplot's code in order to randomize values for RGB/HSL to create a random color for a slice of the pie graph.


My question is, how can I convert the randomized Color into a String, so that I may be able to print an indication that this slice of the pie is colored as such.


Below is a sample code which I have used in order to print the color value into a string, but it only displays the string of the color if I have used the default colors of java.awt.Color, and it displays "unknown" if I am using Mr. Komplot's code.



for (Field f : Color.class.getFields()) {
try {
if (f.getType() == Color.class && f.get(null).equals(c)) {
return f.getName();
}
} catch (java.lang.IllegalAccessException e) {
// it should never get to here
}
}
return "unknown";


Source for Mr. Komplot's code:



http://ift.tt/19kmwfi


Thank you





Aucun commentaire:

Enregistrer un commentaire