Use a random library:
import java.util.Random;
Then create a random generator:
Random rand = new Random();
When the colors are divided into red green and blue, you can create a new random color by creating random primary colors:
// Java 'Color' class takes 3 floats, from 0 to 1. float r = rand.nextFloat(); float g = rand.nextFloat(); float b = rand.nextFloat();
Then, to finally create the color, pass the primary colors to the constructor:
Color randomColor = new Color(r, g, b);
You can also create various random effects using this method, for example, create random colors with a lot of attention to certain colors ... skip less green and blue to create a more pink random color.
// Will produce a random colour with more red in it (usually "pink-ish") float r = rand.nextFloat(); float g = rand.nextFloat() / 2f; float b = rand.nextFloat() / 2f;
Or to ensure that only "light" colors are generated, you can create colors that are always> 0.5 of each color element:
// Will produce only bright / light colours: float r = rand.nextFloat() / 2f + 0.5; float g = rand.nextFloat() / 2f + 0.5; float b = rand.nextFloat() / 2f + 0.5;
There are various other color functions that you can use with the Color class, for example, to make the color brighter:
randomColor.brighter();
An overview of the Color class can be found here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html
Greg Nov 22 2018-10-22 14:28
source share