Need Help Getting A Simple Stop-Watch Working?
So I am experimenting with a little stop-watch object and I can't figure out why it isn't working. I have a gui with the following;
timeinfield is a jtextfield which the user enters the start time of the clock.
timerfield is a jtextfield where the clock is displayed timing.
startbutton is a jbutton where the user clicks to start the clock.
stopbutton is a jbutton where the user clicks to stop the clock.
I want the clock to look like 00.00.00 and keep updating until the user clicks stop. Then I am going to do something with the stop value later on.
Right now, the timerfield just displays Running: 0 seconds.
Nothing else happens, maybe I am doing this wrong for it is my first time trying something like this. I am about to start learning how to use threads so I thought this might help get me started.
Could someone help me write something like this that corresponds to the buttons and areas I have above? This is what I have so far;
Code :
private void startbuttonActionPerformed(java.awt.event.ActionEvent evt) {
String starttim = timeinfield.getText();
long startTime = Long.valueOf(starttim);
boolean running = false;
Timer timer = null;
timer.stop();
long time = (System.currentTimeMillis() - startTime)/1000;
timerfield.setText("Running:" + time + "seconds");
if(running==false){
running = true;
timerfield.setText("Running: 0 seconds");
}
if(stopbutton.isSelected()) {
timer.stop();
running = false;
long endTime = evt.getWhen();
double seconds = (endTime - startTime)/1000.0;
timerfield.setText("Time: " + seconds + "sec.");
}
// going to need timer.stop() while timer is null or null pointer exception occurr
}
Re: Need Help Getting A Simple Stop-Watch Working?
You declare timer but initialize it to null. What do you expect to happen? This is going to cause a NullPointerException every time.