• Post Reply Bookmark Topic Watch Topic
  • New Topic

repaint() with delay  RSS feed

 
Jon Dornback
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having some trouble with swing Graphics. I have some classes similar to the ones below: DrawPanel is a panel with a list of objects to be drawn, and Controller is the user app that controls what's in the list. the user can click on buttons in the Controller to manipulate how many objects are in the list, or highlight them, etc. One button should highlight each object one at a time by changing its color. The problem is that in a tight loop like the one below, the user can't see the individual highlights - only the last one. I tried putting in a delay using both Thread.sleep() and checking the number of milliseconds passed, but both have the same result: the program just "hangs" for however long the delay is, and then displays the end product.
any suggestions on how to handle this? is my current approach valid but in need of tweaking, or should it be done differently?
thanks,
Jon
 
Jon Dornback
Ranch Hand
Posts: 137
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i think i may have found a solution, but would like any feedback if someone knows a better way.
the main problem i was having is that I can't use a Timer or something similar because the data changes each time through the loop, so by the time the Timer executed the update, it wouldn't be the right data any more. The only solution I could think of for that would be to create a deep copy of the ArrayList and give it to the Timer - which would be annoying if not impossible for some objects in the ArrayList (the sample I posted is greatly pruned).
So, what I came up with is that in the ActionListener for the button that runs the loop,
create a new Thread whose run() method performs the sole task of calling the repaint() method so that the GUI is updated. Then, a call Thread.sleep() for a given amount of time so that the GUI stays that way for a moment. This moves the delay out of the GUI display loop so that each update is performed.
is this the "correct" way to do it?
thanks
Jon
 
Nathan Pruett
Bartender
Posts: 4121
IntelliJ IDE Java Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, the sleep/repaint loop has to be in a separate thread, or, as you noticed, the GUI can't repaint. This is because in Swing the event thread controls both handling of events and repaints.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!