3

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.

Boro
  • 7,913
  • 4
  • 43
  • 85
user591790
  • 545
  • 2
  • 15
  • 33

2 Answers2

14

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 );
}
Mikle Garin
  • 10,083
  • 37
  • 59
1

Just because I stumbled upon this recently and I think it's a little bit easier than the existing answer:

public static void main(String[] args) {
    JFrame frame = new JFrame();
    final JTree tree = new JTree();

    JPopupMenu menu = new JPopupMenu();
    menu.add(new JMenuItem("Test"));
    tree.setComponentPopupMenu(menu);
    frame.add(tree);

    frame.pack();
    frame.setLocationRelativeTo(null);
    frame.setVisible(true);
}
Community
  • 1
  • 1
  • 1
    It is definitely easier, but I recall having some issues with it on some specific Swing components. Plus you have no control over how, where and when this menu is displayed - you can only modify contents of the menu. The code that displays menu in your example is hidden deep within L&F implementation (not even component itself or its UI) and it checks `event.isPopupTrigger()` by default which, among other possible issues, doesn't work on some systems. – Mikle Garin Oct 07 '15 at 10:37
  • I'm not that much of a Swing-pro, I just thought the easy solution should not be kept secret if it works in most cases... Thanks for pointing out the issues – Mr Tsjolder from codidact Oct 07 '15 at 15:37
  • Your approach will show popup if user click everywhere inside JTree, which did not wanted in this question. – panoet Oct 25 '22 at 00:25