2009-02-04 61 views
11

Con un JTree, suponiendo que el nodo raíz es nivel 0 y puede haber hasta 5 niveles debajo de la raíz, ¿cómo puedo expandir fácilmente todos los nodos de nivel 1 para que todos los niveles 1 & 2 las ramas y las hojas son visibles pero los niveles 3 y siguientes no lo son?Java JTree expande solo nodos de nivel uno

Respuesta

20

Gracias por la respuesta rápida chicos. Sin embargo, ahora he encontrado la solución simple que estaba buscando. Por alguna razón, simplemente no pude ver DefaultMutableTreeNode.getLevel() en los JavaDocs. FYI lo que estoy haciendo ahora es:

DefaultMutableTreeNode currentNode = treeTop.getNextNode(); 
    do { 
     if (currentNode.getLevel()==1) 
      myTree.expandPath(new TreePath(currentNode.getPath())); 
     currentNode = currentNode.getNextNode(); 
     } 
    while (currentNode != null); 
+0

Esa es una buena solución también: +1. Puede aceptar su propia solución si lo desea (y ponerla en la parte superior de las respuestas), pero sepa que no ganará ningún punto de repetición. – VonC

+0

+1 Buena respuesta simple. –

0

Utilice expand(TreePath) para todos los nodos de nivel 2.

+0

sí, obviamente, pero ¿cómo iba a recorrer todos los nodos saber cuáles son el nivel 2? – garyLynch

+0

Puede hacerlo de la manera en que ya lo hizo, pero ya debería tener la información en su modelo de datos. – Bombe

3

usted tiene algunas clases de utilidad Árbol por ahí que hacen precisamente eso:

Como this one:

public class SimpleNavigatorTreeUtil { 

    /** 
    * Expands/Collapse specified tree to a certain level. 
    * 
    * @param tree jtree to expand to a certain level 
    * @param level the level of expansion 
    */ 
    public static void expandOrCollapsToLevel(JTree tree, TreePath treePath,int level,boolean expand) { 
     try { 
     expandOrCollapsePath(tree,treePath,level,0,expand); 
     }catch(Exception e) { 
e.printStackTrace(); 
     //do nothing 
     } 
    } 

    public static void expandOrCollapsePath (JTree tree,TreePath treePath,int level,int currentLevel,boolean expand) { 
//  System.err.println("Exp level "+currentLevel+", exp="+expand); 
     if (expand && level<=currentLevel && level>0) return; 

     TreeNode treeNode = (TreeNode) treePath.getLastPathComponent(); 
     TreeModel treeModel=tree.getModel(); 
     if (treeModel.getChildCount(treeNode) >= 0) { 
     for (int i = 0; i < treeModel.getChildCount(treeNode); i++ ) { 
      TreeNode n = (TreeNode)treeModel.getChild(treeNode, i); 
      TreePath path = treePath.pathByAddingChild(n); 
      expandOrCollapsePath(tree,path,level,currentLevel+1,expand); 
     } 
     if (!expand && currentLevel<level) return; 
     }  
     if (expand) { 
     tree.expandPath(treePath); 
//   System.err.println("Path expanded at level "+currentLevel+"-"+treePath); 
     } else { 
     tree.collapsePath(treePath); 
//   System.err.println("Path collapsed at level "+currentLevel+"-"+treePath); 
     } 
    } 


} 

Básicamente, es necesario explorar los subnodos hasta que sus criterios (en este caso el nivel de profundidad) se cumple y expande todos los nodos hasta ese punto.

0

Esto debería funcionar -

import javax.swing.*; 
import javax.swing.tree.*; 
import java.awt.BorderLayout; 
import java.awt.event.*; 
import java.util.*; 

public class Tree { 
    public static void main(String[] args) { 
     JPanel panel = new JPanel(new BorderLayout()); 
     final JTree tree = new JTree(); 
     panel.add(new JScrollPane(tree)); 
     JButton btn = new JButton("Press Me"); 
     btn.addActionListener(new ActionListener() { 
      public void actionPerformed(ActionEvent ae) { 
       for (Enumeration e = ((TreeNode)tree.getModel().getRoot()).children();e.hasMoreElements();) { 
        TreeNode tn = (TreeNode)e.nextElement(); 
        tree.expandPath(new TreePath(((DefaultTreeModel)tree.getModel()).getPathToRoot(tn))); 
       } 
      } 
     }); 
     panel.add(btn, BorderLayout.SOUTH); 
     JFrame frame = new JFrame(""); 
     frame.getContentPane().add(panel); 
     frame.setSize(300, 300); 
     frame.setLocation(100, 100); 
     frame.pack(); 
     frame.show(); 
    } 
} 
+0

** ¡ADVERTENCIA! ** 'children()' te ofrece solo un nivel de niños. Necesitas 'breadthFirstEnumeration()'. Entonces funciona –

1

medida que su nivel 1 nodos son todos hijos del nodo raíz, y suponiendo que está utilizando DefaultMutableTreeNode (necesario para la llamada a getPath()), que sólo puede iterar sobre los hijos del nodo raíz de este modo:

Enumeration<?> topLevelNodes 
    = ((TreeNode)tree.getModel().getRoot()).children(); 
while(topLevelNodes.hasMoreElements()) { 
    DefaultMutableTreeNode node 
     = (DefaultMutableTreeNode)topLevelNodes.nextElement(); 
    tree.expandPath(new TreePath(node.getPath())); 
} 
Cuestiones relacionadas