右键单击节点上的JTree和下拉选项 [英] JTree and dropdown options on right clicking nodes
问题描述
我正在尝试使用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) {}
}
});
和PopupCode:
and PopupCode:
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;
}
. (Java中的方法应以小写字母开头!) at the beginning of 这篇关于右键单击节点上的JTree和下拉选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!treePopup
. (methods in Java should start with a lower case letter!)