Why not store the current time in a data type (like a long) when the key is pressed and when the key is released subtract the new time from the old time?
Here's an example--
public class ImprovedClock{
private volatile long first = 0, second = 0;
private volatile boolean startPressed = false, stopPressed = false;
public void start(){
if(!startPressed){
synchronized(this){
first = System.currentTimeMillis();
startPressed = true;
stopPressed = false;
}
}
}
public boolean hasStarted(){
return startPressed;
}
public void stop(){
if(!stopPressed){
synchronized(this){
second = System.currentTimeMillis();
startPressed = false;
stopPressed = true;
}
}
}
public boolean hasStopped(){
return stopPressed;
}
public long getElapsedTime(){
long time = 0;
synchronized(this){
time = second - first;
first = 0;
second = 0;
}
return time;
}
public double getSeconds(){
return ((double)getElapsedTime()/1000);
}
}
import javax.swing.JFrame;
import java.awt.event.KeyEvent;
import java.awt.event.KeyAdapter;
public class TimeMonitorTest extends JFrame{
public TimeMonitorTest(){
final ImprovedClock ic = new ImprovedClock();
addKeyListener(
new KeyAdapter(){
@Override public void keyPressed(KeyEvent ke){
if(!ic.hasStarted()){
ic.start();
System.out.println("Clock started!");
}
}
@Override public void keyReleased(KeyEvent ke){
ic.stop();
System.out.println("Time elapsed: " + ic.getSeconds() + " seconds!");
}
}
);
setSize(300, 300);
setLocation(500, 500);
setVisible(true);
}
public static void main(String... args){
TimeMonitorTest tmt = new TimeMonitorTest();
}
}
To make this work simply focus the pane (by clicking it) and key events will be listened for. Hold down a key then when you release it the seconds the key was held down will be displayed.