2 * Copyright 2000-2009 JetBrains s.r.o.
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
8 * http://www.apache.org/licenses/LICENSE-2.0
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
16 package com
.intellij
.ui
;
19 import javax
.swing
.tree
.TreeModel
;
20 import javax
.swing
.tree
.TreePath
;
22 public class TreeExpandCollapse
{
23 public static void collapse(JTree tree
) {
24 TreePath selectionPath
= tree
.getSelectionPath();
25 tree
.collapsePath(selectionPath
);
28 public static void expand(JTree tree
) {
29 TreePath selectionPath
= tree
.getSelectionPath();
30 tree
.expandPath(selectionPath
);
33 public static void expandAll(JTree tree
) {
34 TreePath path
= tree
.getSelectionPath();
35 if (path
== null) path
= new TreePath(tree
.getModel().getRoot());
36 new ExpandContext(300, 10).expand(tree
, path
);
39 private static class ExpandContext
{
40 private final int myLevelsLeft
;
41 private int myExpansionLimit
;
43 public ExpandContext(int expansionLimit
, int levelsLeft
) {
44 myExpansionLimit
= expansionLimit
;
45 myLevelsLeft
= levelsLeft
;
48 public int expand(JTree tree
, TreePath path
) {
49 if (myLevelsLeft
== 0) return myExpansionLimit
;
50 TreeModel model
= tree
.getModel();
51 Object node
= path
.getLastPathComponent();
52 int levelDecrement
= 0;
53 if (!tree
.isExpanded(path
) && !model
.isLeaf(node
)) {
54 tree
.expandPath(path
);
58 for (int i
= 0; i
< model
.getChildCount(node
); i
++) {
59 Object child
= model
.getChild(node
, i
);
60 if (model
.isLeaf(child
)) continue;
61 ExpandContext childContext
= new ExpandContext(myExpansionLimit
, myLevelsLeft
- levelDecrement
);
62 myExpansionLimit
= childContext
.expand(tree
, path
.pathByAddingChild(child
));
63 if (myExpansionLimit
<= 0) return 0;
65 return myExpansionLimit
;