Swing/PreventNodeExpanding のバックアップ差分(No.10)
- バックアップ一覧
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- バックアップ を表示
- Swing/PreventNodeExpanding へ行く。
- 追加された行はこの色です。
- 削除された行はこの色です。
---
category: swing
folder: PreventNodeExpanding
title: JTreeで展開不可のノードを設定する
tags: [JTree, TreeWillExpandListener, File]
author: aterai
pubdate: 2014-01-27T00:45:37+09:00
description: JTreeで特定のノードだけ展開できないように設定します。
image: https://lh4.googleusercontent.com/-WcBsEg_mxgc/UuUbyvn84EI/AAAAAAAAB-0/iZ6t8_EGeZQ/s800/PreventNodeExpanding.png
---
* 概要 [#summary]
`JTree`で特定のノードだけ展開できないように設定します。
#download(https://lh4.googleusercontent.com/-WcBsEg_mxgc/UuUbyvn84EI/AAAAAAAAB-0/iZ6t8_EGeZQ/s800/PreventNodeExpanding.png)
* サンプルコード [#sourcecode]
#code(link){{
class DirectoryExpandVetoListener implements TreeWillExpandListener {
@Override public void treeWillExpand(TreeExpansionEvent e)
throws ExpandVetoException {
TreePath path = e.getPath();
Object o = path.getLastPathComponent();
if (o instanceof DefaultMutableTreeNode) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) o;
File file = (File) node.getUserObject();
String title = file.getName();
System.out.println(title);
if (title.startsWith(".")) {
throw new ExpandVetoException(e, "Tree expansion cancelled");
}
}
}
@Override public void treeWillCollapse(TreeExpansionEvent e)
throws ExpandVetoException {
// 何もしない(例外を返さない)ので、折り畳みは可能
}
}
}}
* 解説 [#explanation]
- `TreeWillExpandListener`を実装し、`treeWillExpand(...)`メソッド内で、ノード(`File`)の名前がドットで始まる場合、`ExpandVetoException`を発生させることでマウスクリックなどによる展開をキャンセル
-- これらのノードは展開は不可だが、選択自体は可能
- 名前がドットで始まる場合、`DefaultTreeCellRenderer#getTreeCellRendererComponent(...)`内で、そのノードを`setEnabled(false)`で無効状態に変更して描画
* 参考リンク [#reference]
- [https://docs.oracle.com/javase/tutorial/uiswing/events/treewillexpandlistener.html How to Write a Tree-Will-Expand Listener (The Java™ Tutorials > Creating a GUI With JFC/Swing > Writing Event Listeners)]
- [[JTreeのノードを折り畳み不可に設定する>Swing/TreeNodeCollapseVeto]]
* コメント [#comment]
#comment
#comment