[英]store state/expanded nodes of a jtree for restoring state
我正在和JTree合作。
我想知道什么是最好的方法來了解在JTree中擴展哪些節點以便保存其狀態(即保存所有擴展路徑)。 因此,如果我調用model.reload()
,Jtree將不會保持折疊,但我將能夠將其原始狀態恢復到用戶,即,將擴展所有擴展節點。
Santhosh Kumar是Swing Hacks的首選之一。
您需要存儲已展開的TreePath,並在重新加載TreeModel后再次展開它們。 具有后代的所有TreePath都被視為已擴展。 PS如果刪除了路徑,請在重新加載后檢查路徑是否仍然可用。
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);
}
}
我是Java新手,這也讓我瘋狂。 但我想出來了......我想。 以下在我的應用程序中工作正常,但我認為它確實存在一些在某些特殊情況下無法正常工作的風險。
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);
}
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.