Stack Overflow archive
1 score

Creating random colour in Java?

score
1
question views
291.2K
license
CC BY-SA 3.0

Here is a method for getting a random color:

java
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.

Originally posted on Stack Overflow. Public user contributions are licensed under Creative Commons Attribution-ShareAlike.