Right-click context menu for Java JTree?

后端 未结 6 1979
走了就别回头了
走了就别回头了 2020-12-24 12:07

I\'m trying to implement pop-up menus in Java JTree. I\'ve sub-classed DefaultTreeCellRenderer (to change node appearance) and DefaultTreeCellEditor (to create Components to

6条回答
  •  长情又很酷
    2020-12-24 12:57

    Thanks everyone. I knew something was wrong when I was spending that much effort on implementing a simple popup.

    I dismissed this line of thought at first because it felt weird to resort to x- and y- coordinates to find the node I'm looking for, but I guess this is the way to do it.

        // add MouseListener to tree
        MouseAdapter ma = new MouseAdapter() {
            private void myPopupEvent(MouseEvent e) {
                int x = e.getX();
                int y = e.getY();
                JTree tree = (JTree)e.getSource();
                TreePath path = tree.getPathForLocation(x, y);
                if (path == null)
                    return; 
    
                tree.setSelectionPath(path);
    
                My_Obj obj = (My_Obj)path.getLastPathComponent();
    
                String label = "popup: " + obj.getTreeLabel();
                JPopupMenu popup = new JPopupMenu();
                popup.add(new JMenuItem(label));
                popup.show(tree, x, y);
            }
            public void mousePressed(MouseEvent e) {
                if (e.isPopupTrigger()) myPopupEvent(e);
            }
            public void mouseReleased(MouseEvent e) {
                if (e.isPopupTrigger()) myPopupEvent(e);
            }
        };
    
        (...)
    
        JTree tree = new JTree();
        tree.addMouseListener(ma);
    

提交回复
热议问题