Search code examples
javaswingjtreejpopupmenu

showing Popup box on Right click at JTree node swing


I want to show popup box on a right-click at JTree node only, not for the whole JTree component. When user right-clicks on a JTree node then popup box comes up. If he right-clicks a blank space in JTree then it should not come up. So for that how can I detect mouse event only for JTree node. I have searched over the net many times, but couldn't find a solution so please help me.

Thanks.


Solution

  • Here is a simple way:

    public static void main ( String[] args )
    {
        JFrame frame = new JFrame ();
    
        final JTree tree = new JTree ();
        tree.addMouseListener ( new MouseAdapter ()
        {
            public void mousePressed ( MouseEvent e )
            {
                if ( SwingUtilities.isRightMouseButton ( e ) )
                {
                    TreePath path = tree.getPathForLocation ( e.getX (), e.getY () );
                    Rectangle pathBounds = tree.getUI ().getPathBounds ( tree, path );
                    if ( pathBounds != null && pathBounds.contains ( e.getX (), e.getY () ) )
                    {
                        JPopupMenu menu = new JPopupMenu ();
                        menu.add ( new JMenuItem ( "Test" ) );
                        menu.show ( tree, pathBounds.x, pathBounds.y + pathBounds.height );
                    }
                }
            }
        } );
        frame.add ( tree );
    
    
        frame.pack ();
        frame.setLocationRelativeTo ( null );
        frame.setVisible ( true );
    }