Swing/CommonParentTreePath のバックアップ(No.1)
- バックアップ一覧
- 差分 を表示
- 現在との差分 を表示
- 現在との差分 - Visual を表示
- ソース を表示
- Swing/CommonParentTreePath へ行く。
- 1 (2025-05-26 (月) 04:30:11)
- 2 (2025-06-19 (木) 12:41:37)
- 3 (2025-06-19 (木) 12:43:47)
- category: swing folder: CommonParentTreePath title: JTreeで選択したノードの共通の親ノードを取得する tags: [JTree, TreePath, TreeNode] author: aterai pubdate: 2025-05-26T04:25:44+09:00 description: JTree内で選択した複数ノードのTreePathから最長の共通パスを検索することで共通の親TreeNodeを取得します。 image: https://drive.google.com/uc?id=1Jdg36t-_4B0y2uF349YzS7m-N7EZVsyU
Summary
JTree内で選択した複数ノードのTreePathから最長の共通パスを検索することで共通の親TreeNodeを取得します。
Screenshot

Advertisement
Source Code Examples
private void showCommonParent() {
private void showCommonParent() {
JTree tree = (JTree) getInvoker();
Optional.ofNullable(tree.getSelectionPaths())
.filter(paths -> paths.length > 1)
.map(TreeUtils::findCommonParent)
.ifPresent(p -> {
Object node = p.getLastPathComponent();
String title = "common parent";
JOptionPane.showMessageDialog(
tree, node, title, JOptionPane.INFORMATION_MESSAGE);
});
}
// class TreeUtils ...
public static TreePath findCommonParent(TreePath... paths) {
return Stream.of(paths)
.map(TreePath::getPath)
.reduce(TreeUtils::getCommonPath)
.map(TreePath::new)
.orElse(null);
}
public static <T> T[] getCommonPath(T[] node1, T[] node2) {
int min = Math.min(node1.length, node2.length);
for (int len = min; len > 0; len--) {
T[] a1 = Arrays.copyOf(node1, len);
T[] a2 = Arrays.copyOf(node2, len);
if (Arrays.deepEquals(a1, a2)) {
return a1;
}
}
return Arrays.copyOf(node1, 1);
}
View in GitHub: Java, KotlinExplanation
JTree#getSelectionPaths()
で取得した選択TreePath
が複数存在する場合、それらをTreePath#getPath()
でルートノードからのTreeNode
の配列に変換Stream.reduce(...)
でTreeNode
配列を2
つ取り出し、それらをArrays.copyOf(...)
を使用して短いTreeNode
配列の長さに揃えてからArrays.deepEquals(a, b)
で一致するかチェック- 一致しなければ
TreeNode
配列の長さを1
レベル短くして再比較 TreeNode
配列の長さが1
になるまで一致しない場合はルートノードが共通の親TreeNode
となる
- 一致しなければ
Reference
- JTreeのすべてのノードにJCheckBoxを追加する
- java - Common parent of DefaultMutableTreeNode collection - Stack Overflow
TreePath
は使用せず、TreeNode.getParent()
などでTreeNode
のStream
を作成して共通親ノードを探すサンプルなど