gpt4 book ai didi

swing - 右键单击节点上的 JTree 和下拉选项

转载 作者:行者123 更新时间:2023-12-02 08:51:43 26 4
gpt4 key购买 nike

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

这是我所做的:

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:

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)  

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

但是,当我运行该程序时,我得到了子节点和父节点的相同右键单击弹出窗口。

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

最佳答案

不要像 MouseListener 这样低级,而是使用 componentPopupMenu 周围的 api。这样做,一般的做法是在 getPopupLocation 方法中动态配置 componentPopup,一些简单的示例片段:

    JPopupMenu popup = new JPopupMenu();
final Action action = new AbstractAction("empty") {

@Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
};
popup.add(action);
JTree tree = new JTree() {

/**
* @inherited <p>
*/
@Override
public Point getPopupLocation(MouseEvent e) {
if (e != null) {
// here do your custom config, like f.i add/remove menu items based on context
// this example simply changes the action name
TreePath path = getClosestPathForLocation(e.getX(), e.getY());
action.putValue(Action.NAME, String.valueOf(path.getLastPathComponent()));
return e.getPoint();
}
action.putValue(Action.NAME, "no mouse");
return null;
}

};
tree.setComponentPopupMenu(popup);

关于swing - 右键单击节点上的 JTree 和下拉选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8080807/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com