Skip to content
Advertisement

Java swing repainting while computing: animating sorting algorithm

http://www.youtube.com/watch?v=M0cNsmjK33E

I want to develop something similar to the link above using Java Swing. I have the sorting method and did while repaint but when I triggered the sorting, instead of showing the bars slowly sorting itself, it freezes and then unfreezes when the array has been fully sorted.

How do I fix this? Edit: sorry forgot about the codes. its a very simple gui. and another class for sorting which sorts the whole array

JavaScript

Advertisement

Answer

Note: I started writing this before the question was deleted

Most likely your using some looping mechanism and praying that each iteration, the ui with be updated. That’s a wrong assumption. The UI will not be update until the loop is finished. What you are doing is what we refer to as blocking the Event Dispatch Thread(EDT)

See How to use a Swing Timer. Make “iterative” updates in the ActionListener call back. For instance, if you want to animate a sorting algorithm, you need to determine what needs to be updated per “iteration” of the timer callback. Then each iteration repaint the ui.

So your Timer timer could look something like

JavaScript

Your sortOnlyOneItem method should only, well, perform a sort for just one item. And have some sort of flag to check if the sorting is done, then stop the timer.


Other notes:

  • You should be calling super.paintComponent in the paintComponent method, if you aren’t going to paint the background yourself. Generally I always do though.

Here’s a complete example. I’m glad you figured it out on your own. I was working on this example before I saw that you got it.

enter image description here

JavaScript
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement