---
category: swing
folder: TreeLeafIcon
title: JTreeのOpenIcon、ClosedIcon、LeafIconを変更
tags: [JTree, Icon, TreeCellRenderer]
author: aterai
pubdate: 2011-03-14T15:52:42+09:00
description: JTreeのOpenIcon、ClosedIcon、LeafIconの表示を切り替えます。
image: https://lh4.googleusercontent.com/_9Z4BYR88imo/TX24gbN5bHI/AAAAAAAAA30/l8Pn8nUfJiA/s800/TreeLeafIcon.png
---
* 概要 [#summary]
`JTree`の`OpenIcon`、`ClosedIcon`、`LeafIcon`の表示を切り替えます。

#download(https://lh4.googleusercontent.com/_9Z4BYR88imo/TX24gbN5bHI/AAAAAAAAA30/l8Pn8nUfJiA/s800/TreeLeafIcon.png)

* サンプルコード [#sourcecode]
#code(link){{
folderCheck.addActionListener(new ActionListener() {
  @Override public void actionPerformed(ActionEvent e) {
    DefaultTreeCellRenderer r = (DefaultTreeCellRenderer) tree.getCellRenderer();
    if (((JCheckBox) e.getSource()).isSelected()) {
      r.setOpenIcon(r.getDefaultOpenIcon());
      r.setClosedIcon(r.getDefaultClosedIcon());
    } else {
      r.setOpenIcon(emptyIcon);
      r.setClosedIcon(emptyIcon);
    }
    allNodesChanged(tree);
  }
});
}}

* 解説 [#explanation]
- 以下のメソッドを使用してデフォルトアイコンと空アイコン(もしくは`null`)を設定し、表示非表示を切り替え
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#setOpenIcon-javax.swing.Icon- DefaultTreeCellRenderer#setOpenIcon(Icon)]
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#getDefaultOpenIcon-- DefaultTreeCellRenderer#getDefaultOpenIcon()]
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#setClosedIcon-javax.swing.Icon- DefaultTreeCellRenderer#setClosedIcon(Icon)]
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#getDefaultClosedIcon-- DefaultTreeCellRenderer#getDefaultClosedIcon()]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#setLeafIcon-javax.swing.Icon- DefaultTreeCellRenderer#setLeafIcon(Icon)]
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#setLeafIcon-javax.swing.Icon- DefaultTreeCellRenderer#setLeafIcon(Icon)]
-- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/tree/DefaultTreeCellRenderer.html#getDefaultLeafIcon-- DefaultTreeCellRenderer#getDefaultLeafIcon()]
- 各アイコンの幅が変化するため表示を切り替えた後ですべてのノードを再評価する必要がある
#code{{
private static void allNodesChanged(JTree tree) {
  DefaultTreeModel model = (DefaultTreeModel) tree.getModel();
  DefaultMutableTreeNode root = (DefaultMutableTreeNode) model.getRoot();
  Enumeration depth = root.depthFirstEnumeration();
  while (depth.hasMoreElements()) {
    model.nodeChanged((TreeNode) depth.nextElement());
  }
}
}}

* 参考リンク [#reference]
- [[JTreeの展開、折畳みアイコンを非表示にする>Swing/TreeExpandedIcon]]

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