Reputation: 3038
I have a java program with a GUI based on Swing. In the main class there are some computations which are grouped in a separate thread. My problem is : I need to start a stopwatch when those computations begin, show the timer WHILE THEY PROCEEDING, stop as they finish. If I only needed to count the time left I would start the stopwatch in the separate thread do all computations in the main thread and when they finished stopped the stopwatch thread and display the timer. As I know java swing is singlethreaded. So that I can repaint the digiths of the stopwatch in the main swing
Upvotes: 1
Views: 616
Reputation: 3038
First of all, I want to say thank you to everybody.
The problem was solved by usind SwingWorker in such a way: the main swing window I developed as a child of SwingWorker. All the computations were in doInBackground method. While they were proceeding, a timer (which is in a separate thread) was invoked in SwingUtilities.invokeLater. In the done method when all the computations finished the timer was stopped.
Upvotes: 1
Reputation: 205785
I've read that
SwingWorker
seems to be what I need.
I'll endorse @Ernest Friedman-Hill's javax.swing.Timer
suggestion, but this SwingWorker
example is worth exploring. It may help you leverage your existing thread code.
Upvotes: 1
Reputation: 6087
The Swing timer will more or less do the job, but it can be somewhat inaccurate. In fact, the inaccuracy can be noticeable. For instance, if you make your timer with the Swing Timer and then watch the numbers as they tick by, you might notice it isn't always exactly a second in between ticks. In other words the resolution of the timer isn't that great.
An alternative to the Swing Timer is System.nanoTime()
. I always use this. It has much better resolution. It returns the current system time in nano seconds as a long.
Here is a quick example of how you could use this to count by the seconds:
long previousTime = 0L;
int seconds = 0;
while(true)
{
long currTime = System.nanoTime();
if((currTime - previousTime) / 1000000000L >= 1L)
{
previousTime = currTime;
seconds++;
System.out.println("Seconds: " seconds)
}
}
Upvotes: 0
Reputation: 81684
The easiest thing to do would be to use a javax.swing.Timer. It's easy to have a Timer send periodic update events to update the GUI, and it's easy to stop or reset the timer as needed.
Upvotes: 3