Created
March 10, 2019 16:26
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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