# Save a mouse coorinates after a specific number of seconds

I have a specific method that saves my mouse x and y coordinates. I want that mouse coordinates be saved by specific time (for example after 1000ms). How I need to do that in Java? Please add a simple usage example.

 public void mouseMoved(MouseEvent e) {
currentX = e.getX();
currentY = e.getY();

if(enemy.onWall() == true){
public void run() {
saveX = e.getX();
saveY = e.getY();
enemy.setCont(true);
move();
}
},100);
enemy.setOnWall(false);
}
}


But this code saves mouse coorinates immediately and then waits for 1000ms and I have old coordinates.

• I have just edited my code. – user3334375 Sep 19 '14 at 13:38

EDIT

Actually, Timer's schedule method should work in this case - maybe it's running straight away because you have 100ms as your delay time instead of 1000 (from your code above that is).

If you're working in a multi-threaded environment, then make sure you handle possible concurrency issues.

A possible alternative would be to use System.nanoTime()

Declare these variables:

long delay = 1000;
long start = 0;
Point temp;


In the mouseMoved method:

    if(enemy.onWall() == true){
temp = e.getLocation();
start = System.nanoTime();
enemy.setOnWall(false);
}


(is enemy.setOnWall(false); supposed to be called after 1000ms?)

And in your game loop:

if (start > 0 && (System.nanoTime() - start) / 1000000 >= delay) {
saveX = temp.getX();
saveY = temp.getY();
enemy.setCont(true);
move();
start = 0;
}


The "timer" is initiated when you move the mouse and is checked each frame to see if the duration since start was set is at least as long as the delay; if it is, the coordinates set at the start should be applied.

Since you move the mouse frequently, you may want to return the mouseMoved method if a coordinate is already scheduled to be saved.

This way you avoid multiple threads and result in a fairly accurate timed task.

• nanoTime() is a good option here since it's more precise and the "downside" that it's from system start instead of Epoch doesn't matter. – Eben Sep 21 '14 at 0:25