This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I've been fiddling around with some code written by Michael Dunn. The timer is set to display "1 second has passed" when it times out.
As you can see in class XYZ, there is an invokeLater() method, this is because of the call to repaint() in the mouseReleased method (Want the GUI to repaint, before continuing).
When clicking the start timer, we can see the timer outputs "1 second has passed" correctly after 1 second... But when clicking thr click me JLabel, and releasing the mouse, this triggers the timer again, but clearly this doesn't print to screen until the for loop finishes.
in the code, you've created a separate thread for longTask, but the task is wrapped in a SwingUtilities.invokeLater, which brings it back into the EDT, and causing the block.
here's the original class XYZ
note the longTask (the for loop) is performed within the separate thread, then, at the end, updating the label is done in the EDT (by using SwingUtilities)
I've changed XYZ in this (also added a label to show the timer 'count'. click the button, 1 second passes, timerLabel changes to 1 click the label, 1 second passes, timerLabel changes to 2, but the label clicked doesn't change until the longTask finishes (5 seconds) - I also changed this from a System.out.println() to a sleep delay (was causing thread deadlock on my pc)
Joined: Apr 11, 2005
Thanks, so is it possible for me to do the same thing with a search method, or even with it just outputting 1,2,3,4,5,6,... like I had before.
I see that you are using Thread.sleep, which I guess is different to runnning a search method.
If I can't do it, I can't use a timer. This is why I hate threads. Thanks for any advice.
Joined: Apr 11, 2005
I FIXED IT !!!
I got sick of messing about with threads and Timers, so I took a look at the java.util.Timer, I didn't like the look of it at first, but its literally took me 10 minutes to fix the whole timer problem. All I have is..
Just before the code for the search, and it plays its move every 3 seconds. But thanks for everyones help, its very much appreciated. Next time, I will pick the right Timer to start with
Joined: Jun 09, 2003
Good to see you have it working, which is the main thing.
Copy the erroneous code to a backup location, and if/when you get time, try to get it working - swing's timer is designed to work with swing, so there must still be something fundamentally wrong somewhere.
If you can find a cure - what you learn from that will make it worth the effort.