Ubaby Ubaby - 1 month ago 5
Java Question

Why last array was filled with first array values?

I try to hold some value in 1st array, then another value in 2nd array. Trying to print 1st array returns 2nd array values. Why ?

ColorGroups class tries to get two different colors from different locations, but the last array is the same as first.

public class ColorGroups{
private ColorOfPixel colorOfPixel = new ColorOfPixel();
private int[] color1 = new int[3];
private int[] color2 = new int[3];

public ColorGroups(){}

public void setCol(int xIn, int yIn){
color1 = colorOfPixel.getColor(xIn, yIn);
color2 = colorOfPixel.getColor(xIn + 100, yIn + 100);
System.out.println(color1[0] + " " + color1[1] + " " + color1[2]);
System.out.println(color2[0] + " " + color2[1] + " " + color2[2]);
}
}

import java.awt.Color;
import java.awt.Robot;
import java.awt.AWTException;

public class ColorOfPixel{
int[] color = new int[3];

public ColorOfPixel(){}

public int[] getColor(int xIn, int yIn){
// accepts position of color, returns size 3 array of red green blue integers
try{
Robot r = new Robot();
Color x = r.getPixelColor(xIn, yIn);
color[0] = x.getRed();
color[1] = x.getGreen();
color[2] = x.getBlue();
}
catch (AWTException e){
e.printStackTrace();
}
return color;
}
}

Answer

Because color1 reuses a single array:

public class color1
{
    int[] color = new int[3]; // <== Creates one array for this color1 instance
    // ...
}

All that happens in getCol is that it gets filled in (again):

Color x = r.getPixelColor(xIn, yIn);
color[0] = x.getRed();   // <==== Nothing here is creating a new color array
color[1] = x.getGreen();
color[2] = x.getBlue();

If you want to use more than one array, you have to actually create more than one array. That would probably mean removing the color instance member entirely, and creating the array in getCol:

import java.awt.Color; import java.awt.Robot; import java.awt.AWTException;

public class color1
{
    public color1()
    {
    }

    public int[] getCol(int xIn, int yIn)
    {
        // accepts position of color, returns size 3 array of red green blue
        // integers
        int[] color = new int[3]; // Has to be here because of how you're (not) handling exceptions
        try
        {
            Robot r = new Robot();
            Color x = r.getPixelColor(xIn, yIn);
            color[0] = x.getRed();
            color[1] = x.getGreen();
            color[2] = x.getBlue();
        }
        catch (AWTException e)
        {
            e.printStackTrace();
        }
        return color;
    }
}