JTree and dropdown options on right clicking nodes

前端 未结 3 1229
醉话见心
醉话见心 2021-01-15 01:49

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

Here\'s what I\'ve done:

pmTree.addM         


        
相关标签:
3条回答
  • 2021-01-15 02:14

    You check the selected node:

    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;
    }
    

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

    0 讨论(0)
  • 2021-01-15 02:16

    Awesome. I was successfully able to put the setSelectionPath() call inside the override of getPopupLocaiton(). I had been trying to do it inside the ActionListener of my JMenuItem to no avail.

    public Point getPopupLocation( MouseEvent e ) {
        Point point = null;
        if( e != null ) {
            TreePath path = getClosestPathForLocation( e.getX(), e.getY() );
            setSelectionPath( path );
            point = e.getPoint();
        }
        return point;
    }
    
    0 讨论(0)
  • 2021-01-15 02:33

    Don't go as low-level as a MouseListener, instead use the api around componentPopupMenu. Doing so, the general approach is dynamically configure the componentPopup in the getPopupLocation method, some simple example snippet:

        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);
    
    0 讨论(0)
提交回复
热议问题