右键单击节点上的 JTree 和下拉选项 [英] JTree and dropdown options on right clicking nodes

查看:25
本文介绍了右键单击节点上的 JTree 和下拉选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 JTree 并为所有父节点和子节点实现不同的下拉菜单.

I'm trying to use the JTree and implement different drop downs for all the parent nodes and the children nodes.

这是我所做的:

pmTree.addMouseListener(new java.awt.event.MouseAdapter() {
        @Override
        public void mouseClicked(java.awt.event.MouseEvent evt) {
            try {
            if(evt.getButton() == evt.BUTTON1) {
            }
            else if (evt.getButton() == evt.BUTTON3) {
                TreePopup(evt);
                //pmTree.updateUI();
            }
            }catch (Exception e) {}
        }
    });

和弹出代码:

public void TreePopup(java.awt.event.MouseEvent evt) {
    DefaultMutableTreeNode node = (DefaultMutableTreeNode)  pmTree.getLastSelectedPathComponent();
    popup = new JPopupMenu();
    popup.setInvoker(pmTree);
    PopupHandler handler = new PopupHandler(pmTree, popup);
    if(node.getLevel() == 1)
    {
        popup.add(getMenuItem("Parent Node", handler));
    }
    else if(node.getLevel() == 2)
    {
        popup.add(getMenuItem("Child", handler));
     }
     }

和 PopUpHandler:

and PopUpHandler:

public class PopupHandler extends javax.swing.JFrame implements ActionListener {
JPopupMenu popup;
Point loc;

public PopupHandler(JTree tree, JPopupMenu popup) {
    //this.tree = NewJFrame.pmTree;
    this.popup = popup;
    tree.addMouseListener(ma);
}

还有

public void actionPerformed(java.awt.event.ActionEvent evt)  

对于被点击的子节点或父节点.

for the Child or Parent node being clicked.

但是,当我运行程序时,子节点和父节点都会出现相同的右键单击弹出窗口.

However, when I run the program, I get the SAME right click popups for both the child and parent node.

抱歉,代码量很大.我已经坚持了2天,但没有成功.谢谢!

Sorry for the huge chunk of code. I've been stuck with it for 2 days and yet not successful. Thanks!

推荐答案

你检查选中的节点:

DefaultMutableTreeNode node = (DefaultMutableTreeNode)pmTree.getLastSelectedPathComponent();

查看您是否有父"或子"节点.您应该先选择鼠标位置的节点,否则它将不是正确的节点.打电话

to see if you have a "parent" or a "child" node. You should select the node at the mouse position first, otherwise it will not be the right node. Call

TreePath path = pmTree.getPathForLocation(evt.getX(), evt.getY());
if (path != null) {
    pmTree.setSelectionPath(path);
} else {
    return;
}

treePopup 的开头.(Java 中的方法应该以小写字母开头!)

at the beginning of treePopup. (methods in Java should start with a lower case letter!)

这篇关于右键单击节点上的 JTree 和下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆