1 package be
.nikiroo
.fanfix_swing
.gui
.utils
;
3 import java
.util
.ArrayList
;
4 import java
.util
.LinkedList
;
7 import javax
.swing
.JTree
;
8 import javax
.swing
.tree
.TreeModel
;
9 import javax
.swing
.tree
.TreeNode
;
10 import javax
.swing
.tree
.TreePath
;
12 public class TreeSnapshot
{
13 private interface NodeAction
{
14 public void run(TreeNode node
);
18 private TreePath
[] selectionPaths
;
19 private List
<TreePath
> expanded
;
21 public TreeSnapshot(JTree tree
) {
24 selectionPaths
= tree
.getSelectionPaths();
25 if (selectionPaths
== null) {
26 selectionPaths
= new TreePath
[0];
29 expanded
= new ArrayList
<TreePath
>();
30 forEach(tree
, new NodeAction() {
32 public void run(TreeNode node
) {
33 TreePath path
= nodeToPath(node
);
35 if (TreeSnapshot
.this.tree
.isExpanded(path
)) {
47 public void applyTo(JTree tree
) {
48 final List
<TreePath
> newExpanded
= new ArrayList
<TreePath
>();
49 final List
<TreePath
> newSlectionPaths
= new ArrayList
<TreePath
>();
51 forEach(tree
, new NodeAction() {
53 public void run(TreeNode newNode
) {
54 TreePath newPath
= nodeToPath(newNode
);
55 if (newPath
!= null) {
56 for (TreePath path
: selectionPaths
) {
57 if (isSamePath(path
, newPath
)) {
58 newSlectionPaths
.add(newPath
);
59 if (expanded
.contains(path
)) {
60 newExpanded
.add(newPath
);
68 for (TreePath newPath
: newExpanded
) {
69 tree
.expandPath(newPath
);
72 tree
.setSelectionPaths(newSlectionPaths
.toArray(new TreePath
[0]));
75 // You can override this
76 protected boolean isSamePath(TreePath oldPath
, TreePath newPath
) {
77 return newPath
.toString().equals(oldPath
.toString());
80 private void forEach(JTree tree
, NodeAction action
) {
81 forEach(tree
.getModel(), tree
.getModel().getRoot(), action
);
84 private void forEach(TreeModel model
, Object parent
, NodeAction action
) {
85 if (!(parent
instanceof TreeNode
))
88 TreeNode node
= (TreeNode
) parent
;
91 int count
= model
.getChildCount(node
);
92 for (int i
= 0; i
< count
; i
++) {
93 Object child
= model
.getChild(node
, i
);
94 forEach(model
, child
, action
);
98 private static TreePath
nodeToPath(TreeNode node
) {
99 List
<Object
> nodes
= new LinkedList
<Object
>();
102 node
= node
.getParent();
103 while (node
!= null) {
105 node
= node
.getParent();
109 return nodes
.isEmpty() ?
null : new TreePath(nodes
.toArray());
113 public String
toString() {
114 StringBuilder builder
= new StringBuilder();
115 builder
.append("Tree Snapshot of: ").append(tree
).append("\n");
116 builder
.append("Selected paths:\n");
117 for (TreePath path
: selectionPaths
) {
118 builder
.append("\t").append(path
).append("\n");
120 builder
.append("Expanded paths:\n");
121 for (TreePath epath
: expanded
) {
122 builder
.append("\t").append(epath
).append("\n");
125 return builder
.toString();