Reputation: 45
I'm working on a game which involves holding on a button. I want to be able to depending on how long a button was pressed for display an image ie:
x = seconds button was held for
if 3.1 seconds > x > 2.9 seconds
then display image 1
if x < 2.9 or x > 3.1
then display image 2
How would I program this using a mouse listener?
Thank you.
Upvotes: 3
Views: 1209
Reputation: 443
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);
}
}
Upvotes: 0
Reputation: 145
You can use the below code snippet to resolve 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);
}
The holdTime would give you the time in seconds that the mouse was tapped.
Upvotes: 1