【问题标题】:showing Popup box on Right click at JTree node swing在 JTree 节点摇摆处右键单击显示弹出框
【发布时间】:2012-04-23 11:48:11
【问题描述】:

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

谢谢。

【问题讨论】:

    标签: java swing jtree jpopupmenu


    【解决方案1】:

    这是一个简单的方法:

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

    【讨论】:

    • 最好使用MouseEvent#isPopupTrigger,然后使用isRightMouseButton 方法。
    • 这实际上取决于情况。但是对于默认弹出菜单是的,它更好。
    • +1,希望我对 JTree 了解这么多 :-) 。对我来说这是一个很好的答案:-)
    【解决方案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);
    }
    

    【讨论】:

    • 这肯定更容易,但我记得在某些特定的 Swing 组件上遇到了一些问题。此外,您无法控制此菜单的显示方式、位置和时间 - 您只能修改菜单的内容。在您的示例中显示菜单的代码隐藏在 L&F 实现的深处(甚至不是组件本身或其 UI),默认情况下它会检查 event.isPopupTrigger(),除其他可能的问题外,这在某些系统上不起作用。
    • 我不是 Swing 专业人士,我只是认为简单的解决方案在大多数情况下都有效,不应该保密......感谢您指出问题
    猜你喜欢
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-04
    • 1970-01-01
    相关资源
    最近更新 更多