• Post Reply Bookmark Topic Watch Topic
  • New Topic

Showing current time in StopWatch application?  RSS feed

 
John Corkrend
Ranch Hand
Posts: 51
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have built an application that is a simple stopwatch with a start/stop button. All it does is simply gets the time it is when you hit start and the time you hit stop, and find the difference. That works and all but the number of seconds shows up at the end after you hit stop. I want to make it so that when you hit start you see the time going up from 0. I have tried this with a for loop and with a while loop but wasn't quite able to figure it out. I have a variable 'isRunning' that changes from true to false depending on whether the clock is running or not. Here is my code so far.


 
Rob Camick
Ranch Hand
Posts: 2756
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You need to use a Timer to update the label at a specified interval. Read the Swing tutorial on How to Use Timers.

In your Start button you would start the Timer and in your Stop button you would stop the Timer and update the label with the final difference. When the Timer fires you update the label with the difference in time.

Here is a simple example of using a Timer:

 
John Corkrend
Ranch Hand
Posts: 51
Chrome Eclipse IDE Java
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rob Camick wrote:You need to use a Timer to update the label at a specified interval. Read the Swing tutorial on How to Use Timers.

In your Start button you would start the Timer and in your Stop button you would stop the Timer and update the label with the final difference. When the Timer fires you update the label with the difference in time.


Well that didn't really answer my question, you just explained how to use a timer, the whole starting and stopping thing, which I already have done. What I need to know is how to show the current time, if you run my application you see that the time shows up at the end. I want you to be able to see it while the time is going up. I believe I have to use a loop for this but am not quite sure on how to do it.
 
Rob Camick
Ranch Hand
Posts: 2756
12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I want you to be able to see it while the time is going up. I believe I have to use a loop for this but am not quite sure on how to do it.


No you don't use a loop. You use a Timer.

if you run my application you see that the time shows up at the end. I want you to be able to see it while the time is going up.


If you run my example you will see that the label is continuously updated. You just need to modify the code to display whatever you want. Basically the code from your stop button needs to be added to the actionPerformed() method of the Timer.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!