There are different opinions about using System.nanoTime()
.
Have a look : Is System.nanoTime() completely useless?
To be on a safer side you can write your own class that counts the milliseconds using Runnable
interface.
When the mouse is pressed start the Thread containing Runnable
interface.
And interrupt it when mouse is released.
The Runnable
class contains the code that counts the time elapsed.
Consider this snippet:
public class TimeThread implements Runnable{
int timeElapsed = 0;
public int getTimeElapsed() {
return timeElapsed;
}
@Override
public void run(){
while(true){
try{
Thread.sleep(1);
timeElapsed = timeElapsed + 1;
}catch(InterruptedException ex) {
break;
}
}
}
}
Using the above written TimeThread class to calculate the time elapsed during mouse press and release:
Thread timeCalculationThread;
TimeThread timeCalculator;
public void mousePressed(MouseEvent me) {
timeCalculator = new TimeThread();
timeCalculationThread = new Thread(timeCalculator);
timeCalculationThread.start();
}
@Override
public void mouseReleased(MouseEvent me) {
timeCalculationThread.interrupt();
System.out.println("Stopped! time elapsed is "+timeCalculator.getTimeElapsed()+" milliseconds");
try {
timeCalculationThread.join();
System.out.println("Thread has joined");
} catch (InterruptedException ex) {
Logger.getLogger(MouseFrame.class.getName()).log(Level.SEVERE, null, ex);
}
}