[java] 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?

This question is related to java colors random

The answer is


Here is a method for getting a random color:

private static Random sRandom;

public static synchronized int randomColor() {
    if (sRandom == null) {
        sRandom = new Random();
    }
    return 0xff000000 + 256 * 256 * sRandom.nextInt(256) + 256 * sRandom.nextInt(256)
            + sRandom.nextInt(256);
}

Benefits:

  • Get the integer representation which can be used with java.awt.Color or android.graphics.Color
  • Keep a static reference to Random.

If you want pleasing, pastel colors, it is best to use the HLS system.

final float hue = random.nextFloat();
// Saturation between 0.1 and 0.3
final float saturation = (random.nextInt(2000) + 1000) / 10000f;
final float luminance = 0.9f;
final Color color = Color.getHSBColor(hue, saturation, luminance);

package com.adil.util;

/**
* The Class RandomColor.
*
* @author Adil OUIDAD
* @URL : http://kizana.fr
*/
public class RandomColor {      
    /**
    * Gets the random color.
    *
    * @return the random color
    */
    public static String getRandomColor() {
         String[] letters = {"0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F"};
         String color = "#";
         for (int i = 0; i < 6; i++ ) {
            color += letters[(int) Math.round(Math.random() * 15)];
         }
         return color;
    }
}

You seem to want light random colors. Not sure what you mean exactly with light. But if you want random 'rainbow colors', try this

Random r = new Random();
Color c = Color.getHSBColor(r.nextFloat(),//random hue, color
                1.0,//full saturation, 1.0 for 'colorful' colors, 0.0 for grey
                1.0 //1.0 for bright, 0.0 for black
                );

Search for HSB color model for more information.


A one-liner for random RGB values:

new Color((int)(Math.random() * 0x1000000))

Sure. Just generate a color using random RGB values. Like:

public Color randomColor()
{
  Random random=new Random(); // Probably really put this somewhere where it gets executed only once
  int red=random.nextInt(256);
  int green=random.nextInt(256);
  int blue=random.nextInt(256);
  return new Color(red, green, blue);
}

You might want to vary up the generation of the random numbers if you don't like the colors it comes up with. I'd guess these will tend to be fairly dark.


You can instantiate a color with three floats (r, g, b), each between 0.0 and 1.0: http://download.oracle.com/javase/6/docs/api/java/awt/Color.html#Color(float,%20float,%20float).

Using Java's Random class you can easily instantiate a new random color as such:

Random r = new Random();
Color randomColor = new Color(r.nextFloat(), r.nextFloat(), r.nextFloat());

I can't guarantee they'll all be pretty, but they'll be random =)


import android.graphics.Color;

import java.util.Random;

public class ColorDiagram {
    // Member variables (properties about the object)
    public String[] mColors = {
            "#39add1", // light blue
            "#3079ab", // dark blue
            "#c25975", // mauve
            "#e15258", // red
            "#f9845b", // orange
            "#838cc7", // lavender
            "#7d669e", // purple
            "#53bbb4", // aqua
            "#51b46d", // green
            "#e0ab18", // mustard
            "#637a91", // dark gray
            "#f092b0", // pink
            "#b7c0c7"  // light gray
    };

    // Method (abilities: things the object can do)
    public int getColor() {
        String color = "";

        // Randomly select a fact
        Random randomGenerator = new Random(); // Construct a new Random number generator
        int randomNumber = randomGenerator.nextInt(mColors.length);

        color = mColors[randomNumber];
        int colorAsInt = Color.parseColor(color);

        return colorAsInt;
    }
}

I have used this simple and clever way for creating random color in Java,

Random random = new Random();
        System.out.println(String.format("#%06x", random.nextInt(256*256*256)));

Where #%06x gives you zero-padded hex (always 6 characters long).


I know it's a bit late for this answer, but I've not seen anyone else put this.

Like Greg said, you want to use the Random class

Random rand = new Random();

but the difference I'm going to say is simple do this:

Color color = new Color(rand.nextInt(0xFFFFFF));

And it's as simple as that! no need to generate lots of different floats.


If you don't want it to look horrible I'd suggest defining a list of colours in an array and then using a random number generator to pick one.

If you want a truly random colour you can just generate 3 random numbers from 0 to 255 and then use the Color(int,int,int) constructor to create a new Color instance.

Random randomGenerator = new Random();
int red = randomGenerator.nextInt(256);
int green = randomGenerator.nextInt(256);
int blue = randomGenerator.nextInt(256);

Color randomColour = new Color(red,green,blue);

Copy paste this for bright pastel rainbow colors

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);

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to colors

is it possible to add colors to python output? How do I use hexadecimal color strings in Flutter? How do I change the font color in an html table? How do I print colored output with Python 3? Change bar plot colour in geom_bar with ggplot2 in r How can I color a UIImage in Swift? How to change text color and console color in code::blocks? Android lollipop change navigation bar color How to change status bar color to match app in Lollipop? [Android] How to change color of the back arrow in the new material theme?

Examples related to random

How can I get a random number in Kotlin? scikit-learn random state in splitting dataset Random number between 0 and 1 in python In python, what is the difference between random.uniform() and random.random()? Generate random colors (RGB) Random state (Pseudo-random number) in Scikit learn How does one generate a random number in Apple's Swift language? How to generate a random string of a fixed length in Go? Generate 'n' unique random numbers within a range What does random.sample() method in python do?