save mouse clicks in java
I am trying to save the location of the mouse position-on a click.Then i need to analyze its motion to do a specific task.I used the mouseListener interface and when the user clicks the mouse i add the point of clicking to a point array.Then when a user clicks on a button,i tried loop through the array to analyze the motion but i g开发者_运维问答et a null pointer exception at if(points[i].x<points[i+1].x)
Here is the code
Point points[] = new Point[2000];
int numPoints = 0;
void eventOutput(String eventDescription, MouseEvent e) {
System.out.println(eventDescription+" X= "+e.getX()+" Y= "+e.getY());
//xList.add(new Integer(e.getX()));
//yList.add(new Integer(e.getY()));
points[numPoints] = new Point(e.getX(), e.getY());
++numPoints;
}
for(int i=0;i<points.length;i++)
{
System.out.println("In MOO "+points[i].x);
if(points[i].x<points[i+1].x)
{
xInc=true;
if(points[i].y<points[i+1].y)
{
yInc=true;
}
else if(points[i].y>points[i+1].y)
{
yDec=true;
}
}
else if(points[i].x>points[i+1].x)
{
xDec=true;
if(points[i].y<points[i+1].y)
{
yInc=true;
}
else if(points[i].y>points[i+1].y)
{
yDec=true;
}}}}
Could anyone please help me about that.Thanks in advance
You don't want to loop over all of the array -- you only want to loop up to numPoints
, since later entries are null, right? In fact, if you're going to compare an element with the next element, then you actually only want to loop up to i < numPoints-1
, so that you have one more at the end to compare with.
Consider using a List
like an ArrayList
rather than an array -- it would be easier to avoid problems like this.
you must iterate up to numPoints instead of points.length at
for(int i=0;i<points.length;i++)
points.length is total size of array, not the number of elements that contains.
精彩评论