Eine Sache die mich schon einige Zeit stört/interessiert, wie kann ich am Einfachsten einen kompletten JTree aufklappen?
// If expand is true, expands all nodes in the tree.
// Otherwise, collapses all nodes in the tree.
public void expandAll(JTree tree, boolean expand) {
TreeNode root = (TreeNode) tree.getModel().getRoot();
// Traverse tree from root
expandAll(tree, new TreePath(root), expand);
}
private void expandAll(JTree tree, TreePath parent, boolean expand) {
// Traverse children
TreeNode node = (TreeNode) parent.getLastPathComponent();
if (node.getChildCount() >= 0) {
for (Enumeration e = node.children(); e.hasMoreElements();) {
TreeNode n = (TreeNode) e.nextElement();
TreePath path = parent.pathByAddingChild(n);
expandAll(tree, path, expand);
}
}
// Expansion or collapse must be done bottom-up
if (expand) {
tree.expandPath(parent);
} else {
tree.collapsePath(parent);
}
}```
Ich habs beführchtet, so einfach geht das also nicht
Danke
Ich mach das in meinem JXTree so ähnlich. cancelEditing ist ne super Idee vorher.
* Expands all paths in the tree.
*
* @see JTree#expandPath(TreePath)
*/
public void expandAll() {
cancelEditing();
final TreeModel tm = getModel();
final Object root = tm.getRoot();
/* nothing to expand, if no root */
if (root != null) {
expandAllPaths(new TreePath(root), tm);
}
}
/**
* Opens all paths in the given node and all nodes below that.
*
* @param path the tree path to the node to expand
* @see JTree#expandPath(TreePath)
*/
public void expandAllPaths(TreePath path) {
cancelEditing();
expandAllPaths(path, getModel());
}
/**
* Opens all paths in the given node and all nodes below that.
*
* @param path the tree path to the node to expand
* @param treeModel the tree model
* @see JTree#expandPath(TreePath)
*/
protected void expandAllPaths(TreePath path, TreeModel treeModel) {
expandPath(path);
final Object node = path.getLastPathComponent();
final int n = treeModel.getChildCount(node);
for (int index = 0; index < n; index++) {
final Object child = treeModel.getChild(node, index);
if (treeModel.getChildCount(child) > 0) {
expandAllPaths(path.pathByAddingChild(child));
}
}
}
Ebenius