ProgrammingCuber ProgrammingCuber -4 years ago 101
Java Question

How to change the value of a color channel

I am working on a program where I am trying to avoid more than one red color specifically (255,0,0). To add some variation and make it less likely to occur that I get (255,0,0) What I tried to do was this, but I am having trouble assigning the random variable to the specific color channel. How can I do this?

int x = rand.nextInt(1) + 8;
if(color.getRed() == 255 && color.getBlue() == 0 && color.getGreen() == 0){
color.getBlue() = x;
color.getGreen() = x;
}

Answer Source

The statement

color.getBlue() = x;

makes no sense. It's the same as trying to say "0 = x;".

If color references an object of a class that allows you to change its color channels, you should try:

color.setBlue(x);

However, if color is a java.awt.Color, this won't work because java.awt.Color is immutable. Your only choice then would be to create a new Color object like this:

color = new Color(255, x, x);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download