Right-click context menu for Java JTree?

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

    This task is simple to accomplish, the following is all you need:

    //create a class which implements the MouseListener interface and
    //implement the following in your overridden mouseClicked method
    
    @Override
    public void mouseClicked(MouseEvent e) {
    
        if (SwingUtilities.isRightMouseButton(e)) {
    
            int row = tree.getClosestRowForLocation(e.getX(), e.getY());
            tree.setSelectionRow(row);
            popupMenu.show(e.getComponent(), e.getX(), e.getY());
        }
    }
    

    You can then add this custom listener to your desired tree(s).

提交回复
热议问题