Measure how long you held the mouse?

I am working on a game that involves holding a button. I want to be able to depending on how long the button has been pressed to display the image, for example:

Button

x = seconds held for

if 3.1 seconds> x> 2.9 seconds

then displaying image 1

if x <2.9 or x> 3.1

then displayed image 2

How do I program this with a mouse listener?

Thank.

+3


source to share


2 answers


You can use the below code snippet to solve the problem -

double startTime, endTime, holdTime;
boolean flag = false;

@Override
public final void mousePressed(final MouseEvent e) {
    startTime = System.nanoTime();
    flag = true;
}

@Override
public final void mouseReleased(final MouseEvent e) {
    if(flag) {
        endTime = System.nanoTime();
        flag = false;
    }
    holdTime = (endTime - startTime) / Math.pow(10,9);
}

      



HoldTime will give you the time in seconds that the mouse was pressed.

+1


source


There are different opinions about the use System.nanoTime()

. Take a look: Is System.nanoTime () completely useless?

To be on the safer side, you can write your own class that counts milliseconds using an interface Runnable

.

With the mouse pressed, start the Thread containing the interface Runnable

. And interrupt it when the mouse is released.

The class Runnable

contains code that counts the elapsed time.



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 TimeThread class to calculate the time elapsed when the mouse is pressed and released:

       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);
    }
}

      

0


source







All Articles