showing Popup box on Right click at JTree node swing

user591790 picture user591790 · Apr 11, 2012 · Viewed 9.4k times · Source

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.

Answer

Mikle Garin picture Mikle Garin · Apr 11, 2012

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