3

我只想在节点的右键单击上显示弹出框JTree,而不是整个JTree组件。当用户右键单击 JTree 节点时,会出现弹出框。如果他右键单击一个空白区域,JTree那么它不应该出现。因此,为此我如何仅检测JTree节点的鼠标事件。我在网上搜索了很多次,但找不到解决方案,所以请帮助我。

谢谢。

4

2 回答 2

13

这是一个简单的方法:

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 );
}
于 2012-04-11T07:32:30.087 回答
2

只是因为我最近偶然发现了这个,我认为它比现有的答案要容易一些:

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);
}
于 2015-05-31T15:34:08.103 回答