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, KotlinDescription
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
を作成して共通親ノードを探すサンプルなど