File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes synchronizing Swing with data Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "synchronizing Swing with data" Watch "synchronizing Swing with data" New topic

synchronizing Swing with data

Jon Dornback
Ranch Hand

Joined: Apr 24, 2002
Posts: 137
I need some help synchronizing a Swing display with the data being displayed.
I wrote a simple graphing class that extends JPanel, and given an ArrayList of points it plots each point in the JPanel. However, the list of points can be cleared and updated, and since GUI processing happens in a different thread in the JVM, I had to synchronize all the methods that dealt with the ArrayList. This stopped the various exceptions I was seeing that were happening because the size of the ArrayList was changed in the middle of the display loop, but lead to this problem: I am updating the list of points in a tight loop, and want to see the points move as they are updated. Since the methods are synchronized, I don't see the changes at all until after the tight loop ends.
So the question is, how to I maintain data integrity, yet allow the data to be re-displayed each time through the loop?
Sample code below - sorry it is somewhat lengthy even after I pared it down to bare essentials, but should be easy to follow. Thanks in advance!

use the [CODE] tags - it makes it much easier for people to help you.
Leila Algarve

Joined: Apr 13, 2003
Posts: 2
Have you tried to slow down the loop? It might be just too fast for you see anything. Why don't you make the thread sleep just before "map.clearPlots()" ?
Jon Dornback
Ranch Hand

Joined: Apr 24, 2002
Posts: 137
I tried making the thread sleep for half a second, but to no avail. I'm unclear as to exactly how the locking mechanism works, but I think because all the calls to the SimpleGraph are within the same loop in a single method, perhaps the lock isn't being released. Any info on how this works is appreciated!
Jim Yingst

Joined: Jan 30, 2000
Posts: 18671
Make sure your code actually compiles, then post that code.
Comment out the map.clearPlots() entirely, until everything else is working OK.
Fix the while(i<5) loop so it's not infinite.
If there are further problems, insert some print statements for debugging, so you can you can see what parts of the program are getting executed + when.

"I'm not back." - Bill Harding, Twister
I agree. Here's the link:
subject: synchronizing Swing with data
It's not a secret anymore!