Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 543
Elton.fd Avatar asked Nov 22 '10 14:11

Elton.fd


People also ask

How do you create a new color in Java?

To create your own color: Paint - Double click on any color at the bottom of the screen. - Choose "Define Custom Colors". - Select a color and/or use the arrows to achieve the desired color. are the numbers needed to create your new Java color.


1 Answers

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:

randomColor.brighter(); 

An overview of the Color class can be read here: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html

like image 153
Greg Avatar answered Oct 04 '22 23:10

Greg