• category: swing folder: ExpandedDescendants title: JTreeの展開状態を記憶・復元する tags: [JTree, TreePath] author: aterai pubdate: 2013-11-18T00:04:12+09:00 description: JTreeのノードが展開されているかどうかを記憶、復元します。 image: https://lh4.googleusercontent.com/-FcYsZkFYSxE/UojBcoMtHwI/AAAAAAAAB6k/A7D221doy2w/s800/ExpandedDescendants.png

概要

JTreeのノードが展開されているかどうかを記憶、復元します。

サンプルコード

visitAll(tree, rootPath, false); //Collapse all
if (expandedState == null) {
  return;
}
while (expandedState.hasMoreElements()) {
  tree.expandPath(expandedState.nextElement());
}
expandedState = tree.getExpandedDescendants(rootPath);
View in GitHub: Java, Kotlin

解説

上記のサンプルでは、JTree#getExpandedDescendants(TreePath)メソッドを使用して、展開されているノードのTreePathEnumerationに保存しています。復元は一旦すべてのノードを折り畳んでから、JTree#expandPath(TreePath)メソッドを使用してEnumeration<TreePath>から取得したノードを展開しています。

  • 注:
    • 親ノードが閉じている場合、その子ノードの展開状態は記憶していない
      • このサンプルでの例を挙げると、Set 004を展開して、親のSet 001を折り畳んだ状態で、JTree#getExpandedDescendants(TreePath)を使用した場合、戻り値のEnumeration<TreePath>Set 004へのパスは含まれない
    • JTree#getExpandedDescendants(TreePath) (Java Platform SE 7)に書かれている説明がよく分からない(特に前半)が、もしかしたら上記のことを言っているのかもしれない…
If you expand/collapse nodes while iterating over the returned Enumeration this may not return all the expanded paths, or may return paths that are no longer expanded.
返された Enumeration で繰り返している間ノードを展開するか、折りたたむと、このメソッドは展開されたすべてのパスを返すのではなく、それ以上展開されていないパスを返します。

  • JTreeのシリアライズに関するのメモ
//XMLEncoderではデフォルトのJTreeの場合、展開状態などは保存されない
try (XMLEncoder xe = new XMLEncoder(new BufferedOutputStream(new FileOutputStream(xmlFile)))) {
  xe.writeObject(tree);
  //xe.close();
  //...

  //ObjectOutputStreamの場合は、選択状態、展開状態なども保存、復元可能
  ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(file));
  oos.writeObject(tree);
  //...

参考リンク

コメント