Right-click context menu for Java JTree?

后端 未结 6 1926
走了就别回头了
走了就别回头了 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:45

    Call addRightClickListener() to add the right-click context menu listener to your JTree. Both overrides are for proper cross-platform functionality (Windows and Linux differ here).

    private void addRightClickListener()
    {
        MouseListener mouseListener = new MouseAdapter()
        {
            @Override
            public void mousePressed(MouseEvent mouseEvent)
            {
                handleContextMenu(mouseEvent);
            }
    
            @Override
            public void mouseReleased(MouseEvent mouseEvent)
            {
                handleContextMenu(mouseEvent);
            }
        };
    
        tree.addMouseListener(mouseListener);
    }
    
    private void handleContextMenu(MouseEvent mouseEvent)
    {
        if (mouseEvent.isPopupTrigger())
        {
            MyContextMenu contextMenu = new MyContextMenu();
    
            contextMenu.show(mouseEvent.getComponent(),
                    mouseEvent.getX(),
                    mouseEvent.getY());
        }
    }
    

提交回复
热议问题