@ SuppressWarnings ( "unchecked" ) public void synchronize ( DefaultTreeModel treeModel , List < Node < E > > children ) throws IOException , SQLException { assert SwingUtilities . isEventDispatchThread ( ) : ApplicationResources . accessor . getMessage ( "assert.notRunningInSwingEventThread" ) ; if ( children == null ) { // No children allowed while ( getChildCount ( ) > 0 ) treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( getChildCount ( ) - 1 ) ) ; if ( getAllowsChildren ( ) ) { setAllowsChildren ( false ) ; treeModel . reload ( this ) ; } } else { // Children allowed if ( ! getAllowsChildren ( ) ) { setAllowsChildren ( true ) ; treeModel . reload ( this ) ; } // Update the children minimally int size = children . size ( ) ; for ( int index = 0 ; index < size ; index ++ ) { Node < E > child = children . get ( index ) ; E value = child . getValue ( ) ; SynchronizingMutableTreeNode < E > synchronizingNode ; if ( index >= getChildCount ( ) ) { synchronizingNode = new SynchronizingMutableTreeNode <> ( value ) ; treeModel . insertNodeInto ( synchronizingNode , this , index ) ; } else { synchronizingNode = ( SynchronizingMutableTreeNode < E > ) getChildAt ( index ) ; if ( ! synchronizingNode . getUserObject ( ) . equals ( value ) ) { // Objects don't match // If this object is found further down the list, then delete up to that object int foundIndex = - 1 ; for ( int searchIndex = index + 1 , count = getChildCount ( ) ; searchIndex < count ; searchIndex ++ ) { synchronizingNode = ( SynchronizingMutableTreeNode < E > ) getChildAt ( searchIndex ) ; if ( synchronizingNode . getUserObject ( ) . equals ( value ) ) { foundIndex = searchIndex ; break ; } } if ( foundIndex != - 1 ) { for ( int removeIndex = foundIndex - 1 ; removeIndex >= index ; removeIndex -- ) { treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( removeIndex ) ) ; } // synchronizingNode already contains the right node } else { // Otherwise, insert in the current index synchronizingNode = new SynchronizingMutableTreeNode <> ( value ) ; treeModel . insertNodeInto ( synchronizingNode , this , index ) ; } } } // Recursively synchronize the children synchronizingNode . synchronize ( treeModel , child . getChildren ( ) ) ; } // Remove any extra children while ( getChildCount ( ) > size ) { treeModel . removeNodeFromParent ( ( MutableTreeNode ) getChildAt ( getChildCount ( ) - 1 ) ) ; } } }
Synchronizes the children of this node with the provided children while adding and removing only a minimum number of nodes . Comparisons are performed using equals on the value objects . This must be called from the Swing event dispatch thread .