b83503104 wrote:
Hi,
the code to create the list is here:
ArrayList my_list = new ArrayList();
...
public void mouseDragged(MouseEvent evt) {
test_point.x = evt.getX();
test_point.y = evt.getY();
my_list.add(test_point);
System.out.println( test_point.x );
System.out.println( test_point.y );
}
The "test_point" is an instance of this class:
class point2D {
int x;
int y;
}
and declared like this:
point2D test_point = new point2D();
From the println print out I see all test_point.x (generated when the
mouse is dragged) are correct. So I think the values added into the
ArrayList "should" also be correct. But that isn't true as I said in
my original post. Can you see a bug here?
Or does the problem come from test_point?
Thanks!
The above code is missing the declaration of test_point. Based on what
I see above, I would bet it is a instance variable.
The problem is that you keep adding the same instance of test_point to
the list. You modify the instance and add it again. But the list only
keeps a reference to the instance, so it only has a reference to the
same object in every slot.
(Perhaps you are used to C++ and std::vector. If I remember correctly,
vector will make a copy of everything added to it. If you are coming
from a C++ background, a useful analogy is to think of all Java
variables (except primitives) as pointers to objects.)
What you want is to make a new instance of point2D every time:
public void mouseDragged(MouseEvent evt)
{
point2D test_point = new point2D();
test_point.x = evt.getX();
test_point.y = evt.getY();
my_list.add(test_point);
System.out.println( test_point.x );
System.out.println( test_point.y );
}
HTH,
Ray