Swing/ExpandAllNodes のバックアップの現在との差分(No.2)
TITLE:JTreeのノードを展開・折り畳み
JTreeのノードを展開・折り畳み
編集者:Terai Atsuhiro~
作成日:&date
更新日:2022-05-24 (火) 09:57:17
概要
JTree
のすべてのノードに対して、展開、折り畳みを行います。
Screenshot
Advertisement
概要
JTreeのすべてのノードに対して、展開、折り畳みを行います。#screenshot
サンプルコード
#spanend
#spandel
private void visitAll(JTree tree, TreePath parent, boolean expand) {
#spanend
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);
#spandel
}
#spanend
#spandel
#spanend
#spanadd
* サンプルコード [#sourcecode]
#spanend
#spanadd
#code(link){{
#spanend
private void expandAll(JTree tree) {
int row = 0;
while(row<tree.getRowCount()) {
while (row < tree.getRowCount()) {
tree.expandRow(row);
row++;
}
}
#spanadd
#spanend
private void collapseAll(JTree tree) {
int row = tree.getRowCount()-1;
while(row>=0) {
int row = tree.getRowCount() - 1;
while (row >= 0) {
tree.collapseRow(row);
row--;
}
}
#spandel
- &jnlp;
- &jar;
- &zip;
解説
- visitAll(A)
- 再帰的にTreePathを辿って、JTree#expandPath(TreePath)、JTree#pacollapsePath(TreePath)メソッドを実行することで、展開、折り畳みを行っています。
private void visitAll(JTree tree, TreePath parent, boolean expand) {
TreeNode node = (TreeNode) parent.getLastPathComponent(); // children(node).forEach(n -> visitAll(tree, parent.pathByAddingChild(n), expand)); if (!node.isLeaf()) { // Java 9: Enumeration<TreeNode> e = node.children(); Enumeration<?> e = node.children(); while (e.hasMoreElements()) { visitAll(tree, parent.pathByAddingChild(e.nextElement()), expand); } } if (expand) { tree.expandPath(parent); } else { tree.collapsePath(parent); }
}
- 再帰的にTreePathを辿って、JTree#expandPath(TreePath)、JTree#pacollapsePath(TreePath)メソッドを実行することで、展開、折り畳みを行っています。
private void visitAll(JTree tree, TreePath parent, boolean expand) {
- expandAll(B)
- JTreeをリストとみなしてexpandAllでは先頭から順番にJTree#expandRow(int)メソッドを実行しています。
- ループは全展開された時のJTreeの行インデックス数だけ繰り返されます。 }}
- collapseAll(B)
- 末尾から順番にJTree#collapseRow(int)メソッドを実行し、見かけ上すべてのノードを折り畳みます。
- 子ノードは展開されているが、親ノードが折り畳まれている場合、その子ノードは折り畳まれません。
解説
-
expandAll(A)
-
JTree
をリストとみなしてexpandAll
では先頭から順番にJTree#expandRow(int)
メソッドを実行 - ループは全展開された時の
JTree
の行数だけ繰り返す
-
-
collapseAll(A)
- 末尾から順番に
JTree#collapseRow(int)
メソッドを実行し、表示されているすべてのノードを折り畳む - 子ノードは展開されているが親ノードが折り畳まれている場合、その非表示となっている子ノードに対しては折り畳みを実行しない
- 末尾から順番に
-
expandAll(B)
-
visitAll(tree, new TreePath(root), true);
- 再帰的に
TreePath
を辿って展開(JTree#expandPath(TreePath)
メソッド)を実行
-
-
collapseAll(B)
-
visitAll(tree, new TreePath(root), false);
- 再帰的に
TreePath
を辿って折り畳み(JTree#collapsePath(TreePath)
メソッド)を実行
-
参考リンク
- Expanding or Collapsing All Nodes in a JTree Component (Java Developers Almanac Example)
- Expand or collapse a JTree - Real's Java How-to