2010-10-07 17 views
5

Estoy trabajando con JTree.almacenar estado/nodos expandidos de un jtree para restaurar el estado

Me gustaría saber cuál es la mejor manera de saber qué nodos se expanden en un JTree para guardar su estado (es decir, guardar todas las rutas expandidas). De modo que si llamo al model.reload(), el Jtree no se colapsará, pero podré restaurar su estado original al usuario, es decir, se expandirán todos los nodos expandidos.

Respuesta

0

Soy nuevo en Java y esto me llevó frutos secos también. Pero lo descubrí ... creo. A continuación, funciona bien en mi aplicación, pero creo que tiene cierto riesgo de no funcionar como se espera en algunas circunstancias inusuales.

import javax.swing.JTree; 
import javax.swing.tree.TreePath; 

public class TreeState { 

private final JTree tree; 
private StringBuilder sb; 

public TreeState(JTree tree){ 
    this.tree = tree; 
} 

public String getExpansionState(){ 

    sb = new StringBuilder(); 

    for(int i =0 ; i < tree.getRowCount(); i++){ 
     TreePath tp = tree.getPathForRow(i); 
     if(tree.isExpanded(i)){ 
      sb.append(tp.toString()); 
      sb.append(","); 
     } 
    } 

    return sb.toString(); 

} 

public void setExpansionState(String s){ 

    for(int i = 0 ; i<tree.getRowCount(); i++){ 
     TreePath tp = tree.getPathForRow(i); 
     if(s.contains(tp.toString())){ 
      tree.expandRow(i); 
     } 
    } 
} 

} 
1

necesita almacenar los TreePaths que se expandieron y se expanda de nuevo después de volver a cargar el TreeModel. Todos los TreePath que tienen un descendiente se consideran expandidos. PD si eliminó las rutas, verifique después de volver a cargar si la ruta todavía está disponible.

public void reloadTree(JTree jYourTree) { 
    List<TreePath> expanded = new ArrayList<>(); 
    for (int i = 0; i < jYourTree.getRowCount() - 1; i++) { 
     TreePath currPath = getPathForRow(i); 
     TreePath nextPath = getPathForRow(i + 1); 
     if (currPath.isDescendant(nextPath)) { 
      expanded.add(currPath); 
     } 
    } 
    ((DefaultTreeModel)jYourTree.getModel()).reload(); 
    for (TreePath path : expanded) { 
     jYourTree.expandPath(path); 
    } 
} 
Cuestiones relacionadas