Ernie S
Ernie S

Reputation: 131

Setting a Random Color

I am having trouble setting up a random color using a class constant.

When I run the program, (this is just small part of the code) it gives me

method setColor in class Graphics cannot be applied to given types

I am very unfamiliar with how to set colors, can someone please explain?

 public static final int COLOR = (int) (Math.random() * 256);

    for(int i = 1; i <= count; i++)
                {
                    g.setColor(new Color(COLOR), (COLOR), (COLOR));
                    g.drawLine(r.nextInt(MIDX), r.nextInt(MIDY), r.nextInt(MIDX), r.nextInt(MIDY));
                }

Upvotes: 0

Views: 14398

Answers (3)

parapura rajkumar
parapura rajkumar

Reputation: 24403

First of all your Color is not random because R , G and B are all equal so it will be grayish

g.setColor(new Color(RCOMPONENT, GCOMPONENT , BCOMPONENT));

Generate three random ints and do like above

Upvotes: 1

KV Prajapati
KV Prajapati

Reputation: 94645

You have to get three random values between 0 to 255 and then construct the Color object.

int red=20;
int green=33;
int blue=33;
Color color=new Color(red,green,blue);
g.setColor(color);

Upvotes: 0

Zohaib
Zohaib

Reputation: 7116

try this

g.setColor(new Color(COLOR, COLOR, COLOR));

Basically this is the constructor of Color Color(int r, int g, int b) that you are trying to call. r,g,b can have values in the range from 0 to 255. In your case it seems that r,g,b will have same value as you are using same constant.

Upvotes: 3

Related Questions