Hello all. I have a problem with the Timer class in javax.swing. Theoretically, this class is supposed to allow for the use of a background thread. For the program I am working on, I set up a Timer that is supposed to count up until it reaches some user-set variable. While this is counting, the program (using a GUI in swing) is supposed to be going on, doing other stuff. When it reaches a certain point, it is supposed to check if the counter is done. If so, it continues on, if not, it waits until the counter reaches the appropriate point. My problem is 3 fold. 1) The timer is not accurate. For example, code like "new Timer(1000, TimerTemperature).start();" is supposed to create a new Timer event, delaying it 1 second. While it does create the event, it's no where even close to a second, much faster in fact. 2) If the timer is not completed BEFORE going on to the other stuff, the program just freezes a bit farther on in the program. Meaning: the timer is not working properly in the background. It allows the user to go on and do other stuff as it's counting, but when it reaches it's break point, if the user has already continued on, it freezes the whole program. 3) Finally, one way around these problems is to use the sleep method with a Thread. The problem with this though is that it busy waits the whole program (can't do anything while it's paused). The only real gain is that the timing is then accurate but I lose the ability to just run a timer in the background. Plus, if I use the sleep method, the program decides not to update text messages sent to an onscreen textField. So, if anyone has any ideas on what I am doing wrong or what I can do to fix my dilemma, I would be much obliged.
Hi JoLehn, First off you need to change your display name to a first and last name as per the naming policy at JavaRanch. For pure timing, instead of using javax.swing.Timer, you should use java.util.Timer instead. The main reason for using javax.swing.Timer is to ensure that any change to a swing component occurs on the swing event thread since swing components are not thread-safe. As for timing accuracy, forget it. Unless you go to a real time Java implementation you're gonna have to settle for close. With the java.util.Timer you have two timing modes: fixed-delay and fixed-rate. You would probably prefer the second for your problem. Hope this helps Michael Morris
Any intelligent fool can make things bigger, more complex, and more violent. It takes a touch of genius - and a lot of courage - to move in the opposite direction. - Ernst F. Schumacher
Joined: Aug 07, 2002
Thanks for your help, Michael. I will see what I can do.
I’ve looked at a lot of different solutions, and in my humble opinion Aspose is the way to go. Here’s the link: http://aspose.com