Matt
Matt

Reputation: 1

How to make shapes be random colors in java

I'm making a shape generator in java and every time you press add it's supposed to output a shape. I'm able to do that but I can only have it be one color using

rectangle.setBackground(java.awt.Color.magenta);

or any other color but only that one. I want to make a method that will pick from four different colors (magenta, orange, red, yellow) and set the color of the rectangle randomly every time a new rectangle is created. I keep seeing stuff about float but I can't get it to work so is there any way to do it without a float?

Upvotes: 0

Views: 702

Answers (2)

Gor Mkhitaryan
Gor Mkhitaryan

Reputation: 21

The simplest way you can do it is with cases if the colors you want to use are not many.Basically using an integer variable u can generate a random number and set for each number a specific color. lets say red=0 blue=1 green=2. so int color=(int)(math.random()*3) this line of code will give you a random number from 0-2 including 0 . using switch(number){ case 0: #set the color to red

case 1: #set color to blue etc...

Upvotes: 0

Rohit
Rohit

Reputation: 535

Try this

import java.util.Random;

Random rand = new Random();

Color getColor()
{
    //Value between 0 and 1  R               G                 B
    return new Color(rand.nextFloat(),rand.nextFloat(),rand.nextFloat());
}

This function returns a random color every time you call it. Then ,

rectangle.setBackground(getColor());

Upvotes: 1

Related Questions