TITLE:JTreeのノードを展開・折り畳み
#navi(../)
*JTreeのノードを展開・折り畳み [#qe99cde9]
>編集者:[[Terai Atsuhiro>terai]]~
作成日:&date~
更新日:&lastmod;

#contents

**概要 [#t2b09e6b]
JTreeのすべてのノードに対して、展開、折り畳みを行います。

#screenshot

**サンプルコード [#ia645451]
#code{{
private void visitAll(JTree tree, TreePath parent, boolean expand) {
  TreeNode node = (TreeNode)parent.getLastPathComponent();
  if(!node.isLeaf() && node.getChildCount()>=0) {
    Enumeration e = node.children();
    while(e.hasMoreElements()) {
      TreeNode n = (TreeNode)e.nextElement();
      TreePath path = parent.pathByAddingChild(n);
      visitAll(tree, path, expand);
    }
  }
  if(expand) tree.expandPath(parent);
  else       tree.collapsePath(parent);
}

private void expandAll(JTree tree) {
  int row = 0;
  while(row<tree.getRowCount()) {
    tree.expandRow(row);
    row++;
  }
}
private void collapseAll(JTree tree) {
  int row = tree.getRowCount()-1;
  while(row>=0) {
    tree.collapseRow(row);
    row--;
  }
}
}}
-&jnlp;
-&jar;
-&zip;

**解説 [#gee86b85]
- visitAll(A)
-- 再帰的にTreePathを辿って、JTree#expandPath(TreePath)、JTree#pacollapsePath(TreePath)メソッドを実行することで、展開、折り畳みを行っています。

- expandAll(B)
-- JTreeをリストとみなしてexpandAllでは先頭から順番にJTree#expandRow(int)メソッドを実行しています。
-- ループは全展開された時のJTreeの行インデックス数だけ繰り返されます。

- collapseAll(B)
-- 末尾から順番にJTree#collapseRow(int)メソッドを実行し、見かけ上すべてのノードを折り畳みます。
-- 子ノードは展開されているが、親ノードが折り畳まれている場合、その子ノードは折り畳まれません。

**参考リンク [#je145430]
-[[Expanding or Collapsing All Nodes in a JTree Component (Java Developers Almanac Example)>http://www.exampledepot.com/egs/javax.swing.tree/ExpandAll.html]]
-[[Expand or collapse a JTree - Real's Java How-to>http://64.18.163.122/rgagnon/javadetails/java-0210.html]]

**コメント [#d120e1b9]
#comment