[英]Java: When passing a 2d array of custom class into a constructor I lose values in the array
我知道标题的确没有意义,但我想不出更好的措词,请多多包涵。
我将Java与LibGDX结合使用,并尝试从已保存的像素图加载数据以在屏幕上呈现地图。 在像素图中,每个像素代表六边形的颜色(该图是六边形的网格)。
问题是:我正在将来自像素图的数据(特别是颜色)加载到我称为HexInfo的类的数组中。 但是,当我将此数组传递给另一个类以在屏幕上绘制它时,数组中的每个HexInfo项的颜色均为黑色。 以下是一切的设置方法
hexInfo = new HexInfo[cols][rows];
for (int i = 0; i < cols; i++)
{
for (int j = 0; j < rows; j++)
{
Color.rgba8888ToColor(color, savedScreenData.getPixel(i, j));
hexInfo[i][j] = new HexInfo(i,j);
hexInfo[i][j].setColour(color);
hexInfo[i][j].setIsVisible(true);
hexInfo[i][j].setIsOccupied(true);
//It is definitely set because this gives the correct colours
System.out.println(hexInfo[i][j].getColour());
}
}
mapScreen = new MapScreen(hexInfo);
在^处,屏幕上打印的getColour是正确的。
然后,在MapScreen类中,我使用一个for循环为每个hexInfo获取getColour:
public MapScreen(HexInfo[][] hexInfo)
{
cols = hexInfo.length;
rows = hexInfo[0].length;
for (int i = 0; i < cols; i++) {
for (int j = 0; j < rows; j++) {
if (hexInfo[i][j].isOccupied())
System.out.println(hexInfo[i][j].getColour());
}
}
}
但是,这里每种颜色都是黑色。
HexInfo类如下:
public class HexInfo {
private Color colour;
private String owner;
private boolean isOccupied;
private boolean isVisible;
public Color getColour() {
return colour;
}
public String getOwner() {
return owner;
}
public boolean isOccupied() {
return isOccupied;
}
public boolean isVisible() {
return isVisible;
}
public void setIsOccupied(boolean isOccupied) {
this.isOccupied = isOccupied;
}
public void setColour(Color colour)
{
this.colour = colour;
System.out.println("SETTING COLOR IN HEXINFO AS: " + colour); //This also gives correct colour in sysout
}
public void updateOwner(Color color, String owner)
{
System.out.println("setting colour in hexinfo as " + color);
this.colour = color;
this.owner = owner;
isOccupied = true;
}
public void setIsVisible(boolean isVisible) {
this.isVisible = isVisible;
}
public HexInfo(int x, int y)
{
mapCoords = new Vector2(x,y);
colour = new Color(Color.BLACK);
isOccupied = false;
}
}
我已经检查过东西,看不到问题出在哪里。 如果我的代码其余部分都包含该信息,请让我知道您还需要什么其他信息(有很多信息,所以我显然没有包括所有信息)。
它与将数组传递给构造函数无关。
当您调用setColour(...)
, HexInfo
不会复制color
,它只是设置一个引用。 因此,数组的所有成员最终都将指向相同的color
实例,因此它们都将具有最后一个像素的颜色。
像这样更改嵌套的for循环的最内层部分应解决此问题:
hexInfo[i][j] = new HexInfo(i,j);
hexInfo[i][j].setIsVisible(true);
hexInfo[i][j].setIsOccupied(true);
Color.rgba8888ToColor(hexInfo[i][j].getColour(), savedScreenData.getPixel(i, j));
//It is now *really* definitely set because this gives the correct colours
System.out.println(hexInfo[i][j].getColour());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.