Swing/TreeNodePopupMenu のバックアップの現在との差分(No.1)
TITLE:JTreeのノード上でJPopupMenuを表示
Posted by aterai at 2009-06-01
JTreeのノード上でJPopupMenuを表示
JTreeのノード上でクリックした場合のみ、JPopupMenuを表示します。- 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:
概要
JTree
のノード上でクリックした場合のみ、JPopupMenu
を表示します。
- &jnlp;
- &jar;
- &zip;
Screenshot
Advertisement
サンプルコード
サンプルコード
#spandel
static class TreePopupMenu extends JPopupMenu {
#spanend
private TreePath[] tsp;
public TreePopupMenu() {
#spanadd
class TreePopupMenu extends JPopupMenu {
#spanend
protected TreePopupMenu() {
super();
add(new AbstractAction("path") {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null, tsp, "path",
JOptionPane.INFORMATION_MESSAGE);
}
add("path").addActionListener(e -> {
JTree tree = (JTree) getInvoker();
JOptionPane.showMessageDialog(
tree, tree.getSelectionPaths(), "path",
JOptionPane.INFORMATION_MESSAGE);
});
add(new JMenuItem("dummy"));
add("JMenuItem");
}
public void show(Component c, int x, int y) {
JTree tree = (JTree)c;
tsp = tree.getSelectionPaths();
if(tsp!=null) {
#spanadd
#spanend
@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(path!=null && Arrays.asList(tsp).contains(path)) {
if (tree.getSelectionCount() > 0
&& Arrays.asList(tree.getSelectionPaths()).contains(path)) {
super.show(c, x, y);
}
}
}
}
View in GitHub: Java, Kotlin解説
上記のサンプルでは以下の場合、JPopupMenuを表示しています。- JTreeのノードが選択されている
- 選択されたノード上にカーソルがある
解説
上記のサンプルでは、JTree
のノードが選択されている、かつ選択されたノード上にカーソルがある場合のみJPopupMenu
を表示可能に設定しています。