Java Create Random Color

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


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.

Leave a Reply

Your email address will not be published. Required fields are marked *