---
category: swing
folder: TreeNodePopupMenu
title: JTreeのノード上でJPopupMenuを表示
tags: [JTree, JPopupMenu, TreePath]
author: aterai
pubdate: 2009-06-01T15:04:19+09:00
description: JTreeのノード上でクリックした場合のみ、JPopupMenuを表示します。
image: https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTWLWQUjBI/AAAAAAAAAo0/3F3RUbU5sx8/s800/TreeNodePopupMenu.png
---
* Summary [#summary]
`JTree`のノード上でクリックした場合のみ、`JPopupMenu`を表示します。
#download(https://lh6.googleusercontent.com/_9Z4BYR88imo/TQTWLWQUjBI/AAAAAAAAAo0/3F3RUbU5sx8/s800/TreeNodePopupMenu.png)
* Source Code Examples [#sourcecode]
#code(link){{
class TreePopupMenu extends JPopupMenu {
protected TreePopupMenu() {
super();
add("path").addActionListener(e -> {
JTree tree = (JTree) getInvoker();
JOptionPane.showMessageDialog(
tree, tree.getSelectionPaths(), "path",
JOptionPane.INFORMATION_MESSAGE);
});
add("JMenuItem");
}
@Override public void show(Component c, int x, int y) {
if (c instanceof JTree) {
JTree tree = (JTree) c;
TreePath path = tree.getPathForLocation(x, y);
if (tree.getSelectionCount() > 0
&& Arrays.asList(tree.getSelectionPaths()).contains(path)) {
super.show(c, x, y);
}
}
}
}
}}
* Description [#explanation]
* Description [#description]
上記のサンプルでは、`JTree`のノードが選択されている、かつ選択されたノード上にカーソルがある場合のみ`JPopupMenu`を表示可能に設定しています。
* Reference [#reference]
- [https://docs.oracle.com/javase/jp/8/docs/api/javax/swing/JTree.html#getPathForLocation-int-int- JTree#getPathForLocation(...) (Java Platform SE 8)]
* Comment [#comment]
#comment
#comment