Java Create Random Color


We know using java.awt.Color class, different colors (nearly 16 million shades) can be created and applied to graphics or components. Using java.util.Random class, various colors can be produced randomly and applied to any component. In the following program, each button click gives different color to the frame. For generating colors randomly, here we use java.util.Random class.

Two methods exist in Random class to generates integers randomly.

  1. int nextInt(): Returns some integer.
  2. int nextInt(int max): Returns an integer, a values from 0 to a maximum of max.

Following program uses the second method. Refer Random class for other methods.

Example on Java Create Random Color
import java.awt.*;
import java.awt.event.*;
import java.util.Random;
public class RandomColors extends Frame implements ActionListener
{
  public RandomColors() 
  {
    setLayout(new FlowLayout());

    Button btn = new Button("Change Background");
    btn.addActionListener(this);
    add(btn);

    setTitle("Generating Random Colors");
    setSize(300, 300);
    setVisible(true);
  }
  public void actionPerformed(ActionEvent e)
  {
    Random rand = new Random();

    int redValue = rand.nextInt(255);
    int greenValue = rand.nextInt(255);
    int blueValue = rand.nextInt(255);
    System.out.println("Red: " + redValue +", Green: " + greenValue + ", Blue: " + blueValue);

    Color clr = new Color(redValue, greenValue, blueValue);
    setBackground(clr);
  }
  public static void main(String args[])
  {
    new RandomColors();
  }
}


Java Create Random Color
Output screen of Java Create Random Color

int redValue = rand.nextInt(255);
int greenValue = rand.nextInt(255);
int blueValue = rand.nextInt(255);

The nextInt(255) method of Random class generates a random number between 0 to 255, the range required for a color component. Calling the same method again and again returns a different random number. These values are printed at DOS prompt; observe, the screenshot. These values are taken to create a Color object.

Color clr = new Color(redValue, greenValue, blueValue);
setBackground(clr);

The random values are taken and created a Color object clr. The color clr is applied to the frame as background. For every button click, a new set of random values are generated and the frame's background changes.

The event handling and event handling steps used in the above program are explained earlier.

1 thought on “Java Create Random Color”

  1. Your code is slightly wrong. It will never generate a color component (r, g, or b) with a value of 255. The Random.nextInt method’s ‘bound’ parameter is an “exclusive upper bound”. If you want to generate a value from 0 – 255, you need to use random.nextInt(256).

Leave a Comment

Your email address will not be published.