view raw
Elton.fd Elton.fd - 1 year ago 68
Java Question

Creating random colour in Java?

I want to draw random coloured points on a JPanel in a Java application. Is there any method to create random colours?


Use the random library:

import java.util.Random;

Then create a random generator:

Random rand = new Random();

As colours are separated into red green and blue, you can create a new random colour by creating random primary colours:

// 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 colour, pass the primary colours into the constructor:

Color randomColor = new Color(r, g, b);

You can also create different random effects using this method, such as creating random colours with more emphasis on certain colours ... pass in less green and blue to produce a "pinker" random colour.

// 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" colours are generated, you can generate colours that are always > 0.5 of each colour 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 colour functions that can be used with the Color class, such as making the colour brighter:


An overview of the Color class can be read here: