Java Awt Paint方法的变量不一致

发布于 2024-09-28 11:38:43 字数 487 浏览 5 评论 0原文

我不确定出了什么问题,但我的 Paint() 中关于某些变量发生了一些奇怪的情况。

这段代码工作得很好:

public void paint(Graphics g)
{
    Point[] positions = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};
}

但是这个不行,我想要这个,因为我根据用户的选择改变了位置形成:

// declared somewhere
Point[] selectedFormation = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};

public void paint(Graphics g)
{
    Point[] positions = selectedFormation;
}

I'm not sure what is wrong but there's some weird happening in my Paint() concerning some variables.

this code works just fine:

public void paint(Graphics g)
{
    Point[] positions = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};
}

but this one don't, i wanted this one, because im changing position formations on user's selection:

// declared somewhere
Point[] selectedFormation = {new Point(20,50),new Point(60,30),new Point(80,20),new Point(80,30)};

public void paint(Graphics g)
{
    Point[] positions = selectedFormation;
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

失退 2024-10-05 11:38:43

当您执行 positions = selectedFormation 时,您并没有创建 selectedFormation 的副本,您只是将其引用存储到位置中。两者都指向同一个对象(同一个数组)。如果使用 position 更改数组,则它与 selectedFormation 是相同的数组。
使用clone()创建数组的副本:

public void paint(Graphics g)
{
    Point[] positions = selectedFormation.clone();
}

但考虑到clone不会复制数组的元素,两个列表将包含相同的实例。如果仅更改任意点的坐标,则会影响两个列表。在这种情况下,您需要制作列表的深层副本:

public Point[] deepCopy(Point[] array) {
    Point[] copy = new Point[array.length];
    for (int i = 0; i < array.length; i++) {
        copy[i] = new Point(array[i]);
    }
    return copy;
}

可以为此使用泛化...但让其保持简单

when you do positions = selectedFormation you are not creating a copy of selectedFormation, you are just storing a reference of it into position. Both point to the same object (the same array). If the array is changed by using position, it is the same array as selectedFormation.
Use clone() to create a copy of the array:

public void paint(Graphics g)
{
    Point[] positions = selectedFormation.clone();
}

but consider that clone does not copy the elements of the array, both list will contain the same instances. If you only change the coordinates of any point, it will affect both lists. In that case you need to make a deep copy of the list:

public Point[] deepCopy(Point[] array) {
    Point[] copy = new Point[array.length];
    for (int i = 0; i < array.length; i++) {
        copy[i] = new Point(array[i]);
    }
    return copy;
}

could use generalization for this... but lets keep it simple

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文