JAL-1075 sort nodes alphabetically
authorjprocter <jprocter@compbio.dundee.ac.uk>
Sat, 1 Sep 2012 16:46:15 +0000 (17:46 +0100)
committerjprocter <jprocter@compbio.dundee.ac.uk>
Sat, 1 Sep 2012 16:46:15 +0000 (17:46 +0100)
src/jalview/gui/JDatabaseTree.java

index 53fc35c..c6b16b1 100644 (file)
@@ -31,6 +31,7 @@ import javax.swing.tree.DefaultMutableTreeNode;
 import javax.swing.tree.DefaultTreeCellRenderer;
 import javax.swing.tree.DefaultTreeModel;
 import javax.swing.tree.TreeCellRenderer;
+import javax.swing.tree.TreeNode;
 import javax.swing.tree.TreePath;
 import javax.swing.tree.TreeSelectionModel;
 
@@ -117,6 +118,8 @@ public class JDatabaseTree extends JalviewDialog implements KeyListener
       }
       root.add(tn);
     }
+    // and sort the tree
+    sortTreeNodes(root);
     svp = new JScrollPane();
     // svp.setAutoscrolls(true);
     dbviews = new JTree(new DefaultTreeModel(root, false));
@@ -165,6 +168,40 @@ public class JDatabaseTree extends JalviewDialog implements KeyListener
     validate();
   }
 
+  private void sortTreeNodes(DefaultMutableTreeNode root)
+  {
+    if (root.getChildCount()==0)
+    {
+      return;
+    }
+    int count=root.getChildCount();
+    String[] names=new String[count];
+    DefaultMutableTreeNode[] nodes=new DefaultMutableTreeNode[count];
+    for (int i=0;i<count;i++)
+    {
+      TreeNode node = root.getChildAt(i);
+      if (node instanceof DefaultMutableTreeNode)
+      {
+        DefaultMutableTreeNode child=(DefaultMutableTreeNode) node;
+        nodes[i]=child;
+        if (child.getUserObject() instanceof DbSourceProxy) {
+          names[i]=((DbSourceProxy)child.getUserObject()).getDbName().toLowerCase();
+        } else {
+          names[i] = ((String) child.getUserObject()).toLowerCase();
+          sortTreeNodes(child);
+        }
+      } else {
+        throw new Error("Implementation Error: Can't reorder this tree. Not DefaultMutableTreeNode.");
+      }
+    }
+    jalview.util.QuickSort.sort(names,  nodes);
+    root.removeAllChildren();
+    for (int i=count-1;i>=0;i--)
+    {
+      root.add(nodes[i]);
+    }
+  }
+
   private class DbTreeRenderer extends DefaultTreeCellRenderer implements
           TreeCellRenderer
   {