cuber
cuber

Reputation: 371

Adding Colors to a Color array

I am writing a program where I take an image determine the average red channel, green channel and blue channel present in that image. I take these averages and pass them as parameters to a new color. I then want to add this color to an array. I repeat this process 24 times. The problem I face is that when I get a new color and add it to the array the previous colors get erased. I want to preserve the existing colors in the array and add to the one that hasn't been filled yet. Here is what I have tried.

System.out.println("R: "+ rAvg);
System.out.println("G: "+ gAvg);
System.out.println("B: "+ bAvg);


Color newColor = new Color(rAvg, gAvg, bAvg);
Color[] ColorArr = new Color[24];

for(int i = 0; i < ColorArr.length; i++){
     ColorArr[i] = newColor;
        }

System.out.println(Arrays.toString(ColorArr));

Here is the output after one color is added to the array

 R: 206
 G: 0
 B: 0
 [java.awt.Color[r=206,g=0,b=0],java.awt.Color[r=206,g=0,b=0]

Here is the array after I add a new color.

R: 211
G: 178
B: 230
[java.awt.Color[r=211,g=178,b=230], java.awt.Color[r=211,g=178,b=230]

The last color gets overwritten and replaced with the new color instead of going in the next index and preserving the last. How can I fix this so I preserve the entered colors in the array and place the new color the index after the previous?

Upvotes: 1

Views: 3499

Answers (2)

Devendra Lattu
Devendra Lattu

Reputation: 2812

Your logic looks correct. The only thing which you need to take care is creating a new instance of color object every time.

//ColorArr[i] = newColor;                    // Instead of this
ColorArr[i] = new Color(rAvg, gAvg, bAvg);   // Do this for each element in array

You were initially doing Color newColor = new Color(rAvg, gAvg, bAvg); and assign the same newColor instance to all the elements in the ColorArr.

Thus, a single change in the newColor instance was reflecting the change in all its referenced elements in the array.

As @user alayor, rightly suggested to create new instances of Color(rAvg, gAvg, bAvg) with different RGB values.

Upvotes: 1

alayor
alayor

Reputation: 5045

You can restructure your code to something like this:

private Color[] colorArray = new Color[24];
private int currentIndex = 0;

public void addColorToArray(int red, int green, int blue) {
  colorArray[currentIndex++] = new Color(red, green, blue);
}

public void myMethodThatDoThis24Times() {
   addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
   addColorToArray(getRedAverage(), getGreenAverage(), getBlueAverage());
   ...
}

Upvotes: 3

Related Questions