Show popup on right click on JTree node swing

I want to display the popup with just one click of the JTreenode button , and not for the whole component JTree. When the user right-clicks on the JTree node, a popup appears. If he right-clicks a space in JTree, then it should not appear. Therefore, for this, how can I detect a mouse event only for JTreenode. I searched the network many times, but could not find a solution, so please help me.

Thank.

+3
source share
2 answers

Here is an easy 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 );
}
+13
source

, , , , :

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

All Articles