Speed up collapse and expand in JTree

JTree is slow… Google this and you will find it is a well known problem. For one of my application I need to do collapse and expand operations on all nodes of a large JTree. Even with the large model flag set it’s take 20 seconds to expand the whole tree. Profiling the execution with Netbeans profiler we can see that 100% of the time is took be the UI. It seems to propagate changes to the UI after the expand/collapse of each nodes. So a way to speed up this is to remove the UI during the operation:

TreeUI ui = myJTree.getUI();

EDIT 2015-10-17, A comment from Johny that I received by e-mail:

First I wanna thank you for the idea, but also point out that it’s wrong. Yes, the reason that expanding all nodes of a JTree is slow is because the JTree GUI will paint() the updates once for every row it expands. So for thousands of expanded rows it is super slow.

But you cannot do this “solution”. If you setUI(null), you will remove the TreeUI’s critical listeners from the JTree, which means the UI is not aware of rows being expanded or collapsed anymore. So your UI “backup” is out-of-date. Then when you setUI(theOldUi), it will look ok, until you try to add some more rows, then it will cause null pointer exceptions because the GUI internal cached data is out of sync with what happened in the tree while the GUI was disabled.

What you MUST do:

myTree.setUI(new BasicTreeUI()); // or whatever GUI you used before.

but instead of setUI you can just use myTree.updateUI() to instantly set it to the normal default for the current look & feel, which is always what you want unless you’ve made your own custom UI!

Also remember that the setUI() will reset any custom things like custom row indentations, setShowGrid, etc, so you will have to re-apply those too.