Java Awt Paint方法的变量不一致
我不确定出了什么问题,但我的 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当您执行
positions = selectedFormation
时,您并没有创建 selectedFormation 的副本,您只是将其引用存储到位置中。两者都指向同一个对象(同一个数组)。如果使用position
更改数组,则它与 selectedFormation 是相同的数组。使用
clone()
创建数组的副本:但考虑到
clone
不会复制数组的元素,两个列表将包含相同的实例。如果仅更改任意点的坐标,则会影响两个列表。在这种情况下,您需要制作列表的深层副本:可以为此使用泛化...但让其保持简单
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 usingposition
, it is the same array as selectedFormation.Use
clone()
to create a copy of the array: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:could use generalization for this... but lets keep it simple