Skip to content

Instantly share code, notes, and snippets.

@sebastianknopf
Created March 10, 2019 16:26
Show Gist options
  • Save sebastianknopf/57a4fe18d150790e6a432ff884b103ed to your computer and use it in GitHub Desktop.
Save sebastianknopf/57a4fe18d150790e6a432ff884b103ed to your computer and use it in GitHub Desktop.
simple algorithm for storing and re-storing the expansion state of a treeview in javafx
import java.util.HashMap;
import java.util.Map;
import javafx.scene.control.TreeItem;
import javafx.scene.control.TreeView;
public class ExpansionState {
private TreeView treeView;
private Map<Integer, Object> expansionGraph;
public ExpansionState(TreeView treeView) {
this.treeView = treeView;
}
public void storeExpansionState() {
TreeItem rootItem = this.treeView.getRoot();
if(rootItem != null) {
this.expansionGraph = this.calculateExpansionGraph(rootItem);
}
}
public void restoreExpansionState() {
if(this.expansionGraph != null) {
TreeItem rootItem = this.treeView.getRoot();
if(rootItem != null) {
this.applyExpansionGraph(rootItem, this.expansionGraph);
}
}
}
private Map<Integer, Object> calculateExpansionGraph(TreeItem treeItem) {
Map<Integer, Object> expGraph = new HashMap<Integer, Object>();
for(int t = 0; t < treeItem.getChildren().size(); t++) {
TreeItem childItem = (TreeItem) treeItem.getChildren().get(t);
if(childItem.isExpanded()) {
if(childItem.getChildren().size() < 1) {
expGraph.put(t, this.calculateExpansionGraph(childItem));
} else {
expGraph.put(t, true);
}
}
}
return expGraph;
}
private void applyExpansionGraph(TreeItem treeItem, Map<Integer, Object> expansionGraph) {
for(int t = 0; t < treeItem.getChildren().size(); t++) {
if(expansionGraph.containsKey(t)) {
TreeItem childItem = (TreeItem) treeItem.getChildren().get(t);
if(expansionGraph.get(t) instanceof Map) {
Map<Integer, Object> subExpansionGraph = (Map<Integer, Object>) expansionGraph.get(t);
this.applyExpansionGraph(childItem, subExpansionGraph);
} else {
Boolean expanded = (Boolean) expansionGraph.get(t);
childItem.setExpanded(expanded);
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment