2010-10-07 25 views
5

Sto lavorando con JTree.stato del negozio/nodi espansi di un jtree per il ripristino dello stato

Mi piacerebbe sapere qual è il modo migliore per sapere quali nodi sono espansi in un JTree in modo da salvarne lo stato (ad esempio, salvare tutti i percorsi espansi). In questo modo, se chiamo model.reload(), Jtree non rimane collassato, ma potrò ripristinare il suo stato originale all'utente, cioè tutti i nodi espansi verranno espansi.

risposta

8

Santhosh Kumar è uno dei miei ragazzi di riferimento per Swing Hacks.

Risposta: http://www.javalobby.org/java/forums/t19857.html

+1

Il signor Kumar non è un hacker, è un salvatore. Se fosse su SO, il mio rappresentante sarebbe rimasto bloccato a -13. –

0

Sono nuovo di Java e questo mi ha spinto noci pure. Ma l'ho capito ... penso. Qui sotto funziona bene nella mia app, ma penso che abbia qualche rischio di non funzionare come previsto in alcune circostanze insolite.

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

è necessario memorizzare le TreePaths che sono state ampliate ed espandere di nuovo dopo aver ricaricato il TreeModel. Tutti i TreePath che hanno un discendente sono considerati espansi. Post scriptum se hai cancellato i percorsi, controlla dopo aver ricaricato se il percorso è ancora disponibile.

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); 
    } 
} 
Problemi correlati